The Composite design pattern provides a solution:
Define separate
Composite objects
that compose
the objects of a part-whole hierarchy
into a tree structure.
Work through a common Component interface
to treat Leaf
and
Composite objects uniformly.
Describing the Composite design in more detail is the
theme of the following sections.
See Applicability section for all problems Composite can solve.
Leaf objects
and Composite objects if any
into higher-level Composite objects
recursively
(recursive composition).
[BGI]
The resulting structure is a
tree structure
that represents a part-whole hierarchy.
Composite objects:
Composite) that
maintains a container of child
Component objects
(children)
and forwards
requests to these children
(for each child in children: child.operation()).
Component]
that represents both
primitives and their containers."
[GoF, p163]
[BGI]
Leaf objects
and entire Composite object structures
uniformly (that is, clients do not know whether
they are working with Leaf or
Composite objects):
Leaf,
the request is performed
directly.
Composite,
the request is performed on all Component
objects downwards the hierarchy.
Background Information
leaf3,leaf4,leaf5)
into a composite object (composite2),
compose this composite object and same-level leaf objects
(leaf1,leaf2) into a
higher-level composite object (composite1),
and so on recursively
(see the above Sample Object Collaboration).