Minimalist Example of a Composite Pattern | 213
Executing the following statements accesses thethird child of the second child of the
root node; which isleaf 5. The parent ofleaf 5is the second child of the root node
(see Figure 6-4).
var leaf5:Component = root.getChild(2).getChild(3);
var leaf5Parent:Composite = l5.getParent( );
Calling theoperation( ) on the parent ofleaf 5 should give the following output.
composite 2
leaf 3
leaf 4
leaf 5
Implementing the remove method
The primary concern with removing nodes has to do with removing all references to
deleted objects so that the garbage collector can recover the memory they used. For
example, before removing a composite node, all its child nodes need to be deleted. If
one of the child nodes is itself a composite, then the remove method should recur-
sively delete its children as well. Therefore, the remove method will work similar to
theoperation( ) method.
From the previous scenario, it is evident that we need to treat leaf nodes and com-
posite nodes differently when deleting them. Therefore, it’s useful to declare a
getComposite( )method in theComponentclass to return the composite object if it is
indeed a composite, andnullif not. The default behavior would be to returnnull.
The following method would be defined with its default implementation in the
Component class.
internal function getComposite( ):Composite
{
return null;
}
TheCompositeclass would override this method and return the actual composite
object.
override internal function getComposite( ):Composite
{
return this;
}
In addition, the parent references of components should be removed before compo-
nents can be removed. The following method to remove the parent reference should
be defined and implemented in theComponent class.
internal function removeParentRef( ):void
{
this.parentNode = null;
}