212 | Chapter 6: Composite Pattern
root.getChild(2).add(new Leaf("leaf 3"));
root.getChild(2).add(new Leaf("leaf 4"));
root.getChild(2).add(new Leaf("leaf 5"));
// add a child leaf to the root node
root.add(new Leaf("leaf 6"));
root.operation( ); // call operation on root node
Removing Nodes
Implementing theremove( )method in theCompositeclass can be a little tricky. The
safe way to remove nodes is to do it from the parent. In order to implement node
removal, we need to create a reference to its parent from each node.
Creating a parent reference
Because all nodes, excluding the root node, will have parent references, it makes
sense to declare the parent reference, and the methods that access it, in theComponent
class. TheparentNode property can be declared as follows.
protected var parentNode:Composite = null;
Note that theparentNodeproperty is declared as typeComposite, and defaults tonull.
This does introduce a dependency between theComponentandCompositeclasses.
However, the tradeoff is type safety over class dependency. The parent reference is
also declared asprotectedto make it accessible only to the current class and its sub-
classes. Two methods to set and get the parent reference should also be imple-
mented in theComponent class.
internal function setParent(compositeNode:Composite):void
{
this.parentNode = compositeNode;
}
public function getParent( ):Composite
{
return this.parentNode;
}
Note that thegetParent( )method is declared aspublicto make it accessible to cli-
ents. However, thesetParent( )method is declared asinternalto prohibit setting the
parent from outside thepackage. This is important as the parent link should only be
set in theadd( )method implementation in theCompositeclass. Theadd( )method
should be modified as follows to set the parent reference of the child node to the cur-
rent composite node.
override public function add(c:Component):void
{
aChildren.push(c);
c.setParent(this);
}