ActionScript 3.0 Design Patterns

(Chris Devlin) #1

236 | Chapter 6: Composite Pattern


Example 6-20 shows the composite class for the airplane. It extends theSpriteclass


and implements the IPlane interface. The Sprite class extends the


DisplayObjectContainerclass that inherits fromDisplayObject. Therefore, our imple-


mentation follows the composite pattern framework. The significant difference


between the composite and component classes is the implementation of operations.


In theCompositeclass, both thegetWeight( )andgetDamage( )methods iterate across


all their children, and return the aggregate weight and damage for the composite


branch of the hierarchical tree. We do not have to implement any of the child han-


dling methods, as they are inherited from theDisplayObjectContainer class.


Example 6-20. Composite.as


package
{
import flash.display.*;


public class Composite extends Sprite implements IPlane
{
protected var nDamage:Number;
protected var nWeight:Number;


public function Composite(weight:Number, damage:Number = 0)
{
this.nDamage = damage;
this.nWeight = weight;
}


public function getDamage( ):Number
{
var localDamage:Number = nDamage;
for (var i:uint = 0; i < this.numChildren; i++)
{
var child:DisplayObject = this.getChildAt(i);
localDamage += IPlane(child).getDamage( );
}
return localDamage;
}


public function getWeight( ):Number
{
var localWeight:Number = nWeight;
for (var i:uint = 0; i < this.numChildren; i++)
{
var child:DisplayObject = this.getChildAt(i);
localWeight += IPlane(child).getWeight( );
}
return localWeight;
}
}
}

Free download pdf