ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Employing Flexibility in the Template Method | 341

Employing Flexibility in the Template Method


Now that you have a better idea of how the Template Method design pattern’s struc-


ture works, let’s see how it can be usefully employed. In this next example, you’ll see


an implementation that uses the same template method for two different concrete


classes. Figure 9-4 shows the class diagram:


The main abstract class,ShedMaker, includes three operations in thetemplateMethod( )


function. Two are abstract and will be overridden by the subclasses where the details


will be supplied. The third operation is a final function, not to be overridden, and will


be used in all subclasses.


The example looks at what you may need in creating a shed in general, and what


different types of sheds may need. The example develops an algorithm that does the


following:



  • Designs the shed

  • Determines which supplies will be required

  • Stores tools in the completed shed


All sheds can use these steps, but depending on the kind of shed, the details will vary


in certain aspects. In this case, we’re supposing that one shed will be made of wood


and the other of corrugated steel. Because designing with wood is different than


designing for steel, the design operation (doDesign( )) is abstract. Likewise, determin-


ing which supplies you need is different as well, and so thedetermineSupplies( )


function is also abstract. However, no matter what kind of shed is built, storing tools


is the same, and so that function is locked so it won’t be overridden.


To get started, open three new ActionScript files, and enter the code in Examples 9-4


to 9-6. Use the caption names as the filenames, and save all files in the same direc-


tory.


Figure 9-4. Template method with two concrete classes


ShedMaker
templateMethod()
doDesign()
determineSupplies()
storeTools()
doDesign()
determineSupplies()
storeTools()

WoodShed
doDesign()
determineSupplies()

SteelShed
doDesign()
determineSupplies()
Free download pdf