206 | Chapter 6: Composite Pattern
class can define default implementations for both composite and leaf nodes. At a
minimum, the Component class declares: add( ), remove(child:Component), and
getChild(n:int)methods. These methods allow clients to build the composite sys-
tem. TheLeafandCompositeclasses extend theComponentclass and override neces-
sary methods. The default implementation defined in the component usually applies
to the concreteLeafclasses. Because adding, removing, and getting child nodes
aren’t relevant to leaf nodes, the default implementation for these methods in the
Componentclass is to raise an exception (throw an error). However, these methods
should be overridden and implemented in theCompositeclass. Note how a compos-
ite object can be composed of several children of type component. Thechildren
property in the Composite class aggregates child components.
The real power of the composite pattern is evident in how theoperation( )method is
implemented both in theLeafandCompositeclasses in the diagram in Figure 6-2.
Operations that apply to both leaves and nodes are defined in theComponentclass. In
most cases, these operations are defined as abstract methods, forcing both theLeaf
andCompositeclasses to provide implementations. The composite classes need to
provide a recursive implementation for theoperation( )method. It needs to call the
operation( )method in each of its child components referenced by thechildren
property. When we think of hierarchical trees, theoperation( )method call will
traverse the tree calling theoperation( ) method in all child components.
To understand how common operations apply to all children recursively, look at the
similarities between the composite pattern and a mobile (Figure 6-3).
The bars represent composite nodes, and the fish and starfish are leaf nodes. The
interesting aspect of the mobile is to visualize what happens when you touch one of
Figure 6-3. A mobile implements a composite pattern
Bars are composite nodes
Leaf nodes touch () operation