Design Patterns – Creating Objects with Nested Lists of Objects

class-designdesign-patternsobject-oriented

In terms of good OOP design, what is the best way to structure code that is just containers of list of objects that contains other lists of objects that also are just other containers?

Example: A Cookbook owns a list of Chapters that owns a list of Recipes that owns a list of Directions. Each object is a different layer within a whole. For clarity, I use the word "list" to refer to any data structure used to store multiple objects.

I've come across this Russian doll problem of nested objects inside of nested objects many times. I've tried passing the bottom level objects through the nest hierarchy and also tried writing methods that pass information down to the bottom nested object. My structure always feels messy because the intermediate classes are filled with methods that do nothing more than passing either objects or information.

An addition due to confusion expressed in the comments:
I'm looking for direction in things to study for handling a general type of problem. I'm not asking for a solution to a specific coding problem that I have in front of me. I wasn't expecting a "one answer to rule them all", but more of "use A design pattern for X situations but use B design pattern for Y situations and beware of Z." The example is for providing a general context, not a specific one.

Best Answer

One way to make it easier is that all classes implement the same interface so you can treat them indistinctly. Theres a known pattern for this:

enter image description here

The good news is that as this creates a tree. You can then write, in an external managing class, recursive methods to look up items.

For example you could write a method findAndAdd(String tagToFind, Component componentToAdd);

To the base interfaces documented in the pattern you should add a tagMatches(String tag) as well as all common getters and setters so you can, again, treat items indistincltly of their class.

I would add hasChild() and nextChild() methods to implement iterations.

Related Topic