ActionScript 3.0 Design Patterns

(Chris Devlin) #1

210 | Chapter 6: Composite Pattern


TheMainclass shown in Example 6-4 represents theclient. It creates a compositeroot


node and adds several composite and leaf nodes to it. The resulting composite struc-


ture is shown graphically in Figure 6-4.


TheMainclass constructor ends with a call to theoperation( )method on the root


node. This method recursively traces the names of all subsequent components in the


structure. The following is the output from this operation.


Example 6-4. Main.as


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
}
}
}


Figure 6-4. Composite tree structure built by the client


root

Composite 1 Composite 2 leaf 6

leaf 1 leaf 2 leaf 3 leaf 4 leaf 5
Free download pdf