ActionScript 3.0 Design Patterns

(Chris Devlin) #1

88 | Chapter 2: Factory Method Pattern


Thedraw( )method takes four parameters: the kind of shape to be created, the stage


object, and the shape’s X and Y location. Even though the shape widget classes draw


the shapes, they’re not visible until added to thedisplay listof the stage via the


addChild( )method. Clients will pass an instance of theStageobject as the display


object container to draw shapes on the stage. The concrete creator classes


UnfilledShapeCreator (Example 2-27) and FilledShapeCreator (Example 2-28)


extend theShapeCreator(Example 2-26) class and implement thecreateShapefac-


tory method.


Example 2-26. ShapeCreator.as


package shapecreators
{
import flash.display.DisplayObjectContainer;
import flash.errors.IllegalOperationError;


// ABSTRACT Class (should be subclassed and not instantiated)
public class ShapeCreator
{
public function draw(cType:uint, target:DisplayObjectContainer,
xLoc:int, yLoc:int):void {
var shape = this.createShape(cType);
shape.drawWidget( );
shape.setLoc(xLoc, yLoc); // set the x and y location
target.addChild(shape); // add the sprite to the display list
}


// ABSTRACT Method (must be overridden in a subclass)
protected function createShape(cType:uint):ShapeWidget
{
throw new IllegalOperationError("Abstract method:
must be overridden in a subclass");
return null;
}
}
}


Example 2-27. UnfilledShapeCreator.as


package shapecreators
{
public class UnfilledShapeCreator extends ShapeCreator
{
public static const CIRCLE :uint = 0;
public static const SQUARE :uint = 1;


override protected function createShape(cType:uint):ShapeWidget
{
if (cType == CIRCLE)
{
trace("Creating new circle shape");
return new CircleWidget( );
} else if (cType == SQUARE) {

Free download pdf