Minimalist Example of a Composite Pattern | 209
method by tracingsName. Whenoperation( )is called in a leaf node, it will output its
name in the output panel.
TheCompositeclass extends theComponentclass. It also declares a property called
sNamethat holds the name of the composite node and sets it to the value passed to it
in the parameterized constructor. A unique feature of theCompositeclass is that it
needs to define a structure to hold references to child components and implement
the methods that operate on child nodes. The simplest structure to hold references to
child nodes is an array. The array calledaChildrenis initialized in the constructor.
Whenever a component is added to a composite node via theadd(c:Component)
method, it’s added to theaChildrenarray using thepush( )method. Theoperation( )
method is also unique in the sense that, it not only implements it by tracingsName,
but callsoperation( )in all of its children. This ensures that theoperation( )method
call recursively traverses all child nodes in the tree structure.
Example 6-3. Composite.as
package
{
public class Composite extends Component
{
private var sName:String;
private var aChildren:Array;
public function Composite(sNodeName:String)
{
this.sName = sNodeName;
this.aChildren = new Array( );
}
override public function add(c:Component):void
{
aChildren.push(c);
}
override public function operation( ):void
{
trace(this.sName);
for each (var c:Component in aChildren)
{
c.operation( );
}
}
}
}