ActionScript 3.0 Design Patterns

(Chris Devlin) #1

416 | Chapter 11: Strategy Pattern


Contexts for String Strategies


You can think of the context classes as theclientsfor the strategies. They use the dif-


ferent strategies. Often, you will hear that a clienthas-abehavior. Whenever a client


class delegates to a delegate class, such as the strategy classes in Figure 11-4, ithas-a


behavior generated by the strategy class. In this application, the context classes rep-


resent the client classes for the strategy classes.


Like all context classes, theStringCheckerclass in Example 11-21 sets a reference to


the two strategy interfaces,StringWorkandSortWork. In addition, it has functions,


workStrings( )andworkSorts( )that constitute the methods used to delegate work to


the strategies.


In addition to having reference properties and methods, the context class includes


setter operations, setString( ) and setSort( ), to dynamically set strategies to


instances of the context classes.


Next, in Examples 11-22 and 11-23, two concrete context classes extend the pri-


mary context class. Note that they inherit the references to the strategies,


Example 11-21. StringChecker.as


package
{
//Context class
class StringChecker
{
protected var stringWork:StringWork;
protected var sortWork:SortWork;
public function StringChecker( ):void
{
}


public function workStrings(s:String):String
{
return stringWork.stringer(s);
}
public function workSorts(a:Array):Array
{
return sortWork.sorter(a);
}
public function setString(sw:StringWork):void
{
stringWork=sw;
}
public function setSort(sow:SortWork):void
{
sortWork=sow;
}
}
}

Free download pdf