214 | Chapter 6: Composite Pattern
The defaultremove(c:Component)method declared with its default implementation in
the Component class is overridden and implemented in the Composite class
(Example 6-5).
Theremove( )method takes one parameter that is an instance of theComponent
class. Based on the passed component instance, theremove( )method has to deal
with two situations: (a) what to do when the component to delete is the current
object, and (b) what to do if it isn’t. If the passed component is the current object,
then the current object has to recursively remove all child components (lines 6-9),
and then remove references to its parent (line 11) and children (line 10). In the sec-
ond scenario, if the passed component is not the current object, it’s assumed to be
one of its children. In this case, the program loops though all its child nodes (lines
13–20) and checks if one of its children needs to be removed. If so, it removes the
child component (line 17), and deletes the reference to the removed child from the
aChildren array (line 18).
Theremove( )method usessafeRemove( ), shown in Example 6-6, to safely remove
child components. ThesafeRemove( )method first checks if the passed component is
a composite, and if so, calls its remove method. If the passed component is not a
composite (it’s a leaf node), it removes its parent reference.
Example 6-5. The remove( ) method
1 override public function remove(c:Component):void
2 {
3 if (c === this)
4 {
5 // remove all my children
6 for (var i:int = 0; i < aChildren.length; i++)
7 {
8 safeRemove(aChildren[i]); // remove children
9 }
10 this.aChildren = []; // remove references to children
11 this.removeParentRef( ); // remove my parent reference
12 } else {
13 for (var j:int = 0; j < aChildren.length; j++)
14 {
15 if (aChildren[j] == c)
16 {
17 safeRemove(aChildren[j]); // remove child
18 aChildren.splice(j, 1); // remove reference
19 }
20 }
21 }
22 }