Minimalist Example of a Composite Pattern | 207
the components. We can think oftouch( )as a common operation that applies to all
components in the mobile. Generally, the touch operation makes the mobile compo-
nent rotate. If you touch a composite node, it will rotate not only itself, but all its
children as well. Touching a leaf node such as a fish will rotate only that compo-
nent, as leaf nodes have no children. The fact that the client manipulating the com-
posite structure does not have to worry about whether the operation’s being carried
out on a leaf or a composite node is one of the key features of the composite pattern.
Key Features of the Composite Pattern
The composite pattern streamlines the building and manipulation of comple xstruc-
tures that are composed of several related pieces.
- Complex structures are built as hierarchical trees.
- The components of the structure can be individual components (primitives or
indivisible objects) or composite components that hold a collection of other
components. - They allow clients to treat both individual components (leaf nodes) and compos-
ite components (composite nodes) the same way, simplifying the interface.
Minimalist Example of a Composite Pattern
This example implements the composite shown in the class diagram in Figure 6-2.
TheComponent.as file (Example 6-1) contains the Component abstract class that
defines the interface for both leaf and composite nodes. The Leaf.as file
(Example 6-2) contains theLeafclass, and theComposite.asfile (Example 6-3) con-
tains theCompositeclass. BothLeafandCompositeclasses extend theComponentclass
and provide necessary implementations. TheMain.asfile (Example 6-4) contains the
client classMain (also known as thedocument class for the Flash document).
Example 6-1. Component.as
package
{
import flash.errors.IllegalOperationError;
// ABSTRACT Class (should be subclassed and not instantiated)
public class Component
{
public function add(c:Component):void
{
throw new IllegalOperationError
("add operation not supported");
}
public function remove(c:Component):void
{