ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Example of a Composite Pattern | 211

root
composite 1
leaf 1
leaf 2
composite 2
leaf 3
leaf 4
leaf 5
leaf 6

It is important to note that theclientsees only the interface defined by theComponent


class. The client doesn’t need to differentiate between composite and leaf nodes, and


isn’t tied to how the operation( )method is implemented. It can simply call


operation( ) on any leaf or composite node and get consistent results.


Accessing Child Nodes


You may have noticed that we didn’t override and implement thegetChild(n:int)


method in theCompositeclass. However, this method’s very important to the compos-


ite pattern, as it allows the client to develop a composite structure by not declaring


variables, as in the previous example. This ensures proper garbage collection when


removing nodes. Garbage collection allows the application to recover memory and


resources allocated to deleted nodes, and will be discussed in more detail later in the


chapter. ThegetChild( )method allows the client to access the children of any com-


posite node. The followinggetChild( ) method is implemented in theComposite class.


override public function getChild(n:int):Component
{
if ((n > 0) && (n <= aChildren.length))
{
return aChildren[n-1];
} else {
return null;
}
}

The parameterizedgetChild( )method returns the child object by the position indi-


cated by the parametern(inde xstarts from 1). After doing a range check, the method


returns the child node ornullif no children exist. The client can now leverage the


getChild( ) method and build the same composite structure more efficiently.


// create root node
var root:Composite = new Composite("root");

// add a node to root
root.add(new Composite("node 1"));
root.getChild(1).add(new Leaf("leaf 1"));
root.getChild(1).add(new Leaf("leaf 2"));

// add another node
root.add(new Composite("node 2"));
Free download pdf