ActionScript 3.0 Design Patterns

(Chris Devlin) #1
What Is the Composite Pattern? | 205

objects and composite objects the same way. For example, when adding, or remov-


ing a component, the client doesn’t have to bother with figuring out if the object is a


primitive or composite object. The client can just as easily remove the engine or a tire


through a common interface.


A useful way to understand the composite pattern is to think of comple xcomposite


objects as hierarchical trees. We’re talking about upside-down trees as in Figure 6-1,


where the system begins with a root node and cascades down, subdividing into sev-


eral branches.


In Figure 6-1, the nodes that contain other components are composite objects. The


leaf nodes are indivisible or primitive components that cannot have any children.


Each leaf node is achildof a composite node and each composite node can have


multiple children, including other composite nodes. Likewise, the composite node


that’s immediately up the hierarchy from a leaf is called itsparent. As shown in the


class diagram in Figure 6-2, the composite pattern provides a common interface to


deal with both composite and leaf nodes.


The common interface for both composite and leaf nodes is theComponentclass. The


component class is usually defined as an abstract class. Therefore, theComponent


Figure 6-1. A hierarchical tree structure showing nodes and leaves


Figure 6-2. Class diagram of a composite pattern


root node (Composite node)

composite nodes

leaf nodes

Client Component
add()
remove(Component)
getChild(int)
operation()

for each child in children
child.operation()

Composite
add()
remove(Component)
getChild(int)
operation()

Leaf
operation()

children
Free download pdf