Minimalist Example of a Composite Pattern | 215
Following the proper sequence when removing parent and child references is essen-
tial, so that deleted objects are left isolated without incoming or outgoing references.
This is a necessary condition for the garbage collector to dispose of the object and
recycle the memory used by it.
Building and Manipulating a Composite Structure
Let’s test how theremove( ) method works by building the composite structure
shown in the first column of Figure 6-4 and removing selected leaves and composite
nodes. From theclient, execute the statements in Example 6-7.
Example 6-6. The safeRemove( ) method
private function safeRemove(c:Component)
{
if (c.getComposite( ))
{
c.remove(c); // composite
} else {
c.removeParentRef( );
}
}
Example 6-7. Main.as (client code to remove nodes)
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main( )
{
var root:Composite = new Composite("root");
// create a node
var n1:Composite = new Composite("composite 1");
n1.add(new Leaf("leaf 1")); // add a child leaf
n1.add(new Leaf("leaf 2")); // add a child leaf
root.add(n1); // add node to root as child
// create another node
var n2:Composite = new Composite("composite 2");
n2.add(new Leaf("leaf 3")); // add a child leaf
n2.add(new Leaf("leaf 4")); // add a child leaf
n2.add(new Leaf("leaf 5")); // add a child leaf
root.add(n2); // add node to root as child
// add a child leaf to the root node
root.add(new Leaf("leaf 6"));
root.operation( ); // call operation on root node