ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Example | 71

The product classes are defined asinternal(the default class attribute in Action-


Script 3.0). This means that they’re not publicly visible. They can only be called from


within theexample package. Now, let’s examine the creator classes.


Creator Classes


Example 2-4 through Example 2-6 show the creator classes. As with the product


classes, all creators belong to the packageexample. The creator classes are defined as


public, which indicates that they are publicly accessible from outside the package.


The creator class, as indicated by the comments, should behave as an abstract class.


It should be subclassed and not be instantiated. It also defines the factory method


that should behave as an abstract method. Note that the two concrete creator classes


CreatorA andCreatorB extend Creator. They also override and implement the


factoryMethod( )method, each returning a corresponding product object. In addi-


tion, thefactoryMethod( )declared in theCreatorclass has to returnnullto prevent


a compile-time error. It will also throw anIllegalOperationErrorif called directly.


This is a runtime check to make sure that this method is overridden.


Example 2-4. Creator.as


package example
{
import flash.errors.IllegalOperationError;


// ABSTRACT Class (should be subclassed and not instantiated)
public class Creator
{
public function doStuff( ):void
{
var product:IProduct = this.factoryMethod( );
product.manipulate( );
}


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


Example 2-5. CreatorA.as


package example
{
public class CreatorA extends Creator
{
override protected function factoryMethod( ):IProduct
{

Free download pdf