ActionScript 3.0 Design Patterns

(Chris Devlin) #1

208 | Chapter 6: Composite Pattern


TheComponentclass should behave as an abstract class and should not be instanti-


ated. It also defines the abstract interface for managing child components, and pro-


vides default implementations for theadd(c:Component),remove(c:Component)and


getChild(n:int) methods. The default implementations for these methods are


designed for leaf nodes and will raise an exception by throwing an


IllegalOperationError. This should be the case as leaf nodes cannot have children


and should not implement operations that deal with child nodes. In addition, the


operation( )method is defined as an abstract method without implementation. It is


left up to the classes that subclassComponent to provide an implementation for it.


TheLeafclass extends theComponentclass. It declares a property calledsNamethat


holds the name of the leaf. It also implements a parameterized constructor that takes


a string value that’s then set to thesNameproperty. It implements theoperation( )


throw new IllegalOperationError
("remove operation not supported");
}


public function getChild(n:int):Component
{
throw new IllegalOperationError
("getChild operation not supported");
return null;
}


// ABSTRACT Method (must be overridden in a subclass)
public function operation( ):void {}


}
}


Example 6-2. Leaf.as


package
{
public class Leaf extends Component
{
private var sName:String;


public function Leaf(sNodeName:String)
{
this.sName = sNodeName;
}


override public function operation( ):void
{
trace(this.sName);
}
}
}


Example 6-1. Component.as (continued)

Free download pdf