What Is the Template Method Pattern? | 333
function navigateVehicle( ): void
{
//nothing here
}
//Concrete function
function drinkCoffee( )
{
trace("Drinking coffee on the way to work ");
}
//End of class
The Template Method does not require a concrete function. However, the example
illustrates that if you have one that’s needed in all instantiations of the template
method, it’s handy to have.
Key Features
In general, the Template Method design pattern is a flexible algorithm-maker cen-
tered around the domain class where the algorithm’s defined. The following features
characterize the Template Method design pattern:
- Uses inheritance for behavior distribution between classes
- Allows subclasses to provide details for some operations in general algorithm
- Uses inverted control structure—parent class calls operations of a subclass
- Specifies the steps of an algorithm and locks the order of operations in the
algorithm - Allows for optional “hook” operations for extensions at specified points
In the Behavior grouping of design patterns, the GoF specifies only two patterns
based oninheritanceinstead of composition, and the Template Method is one.
Because ActionScript 3.0 doesn’t have true abstract classes, you have to remember
not to implement the main abstract class. However, you can program to the abstract
classes interface (supertype), and not the implementation. This chapter’s examples
show this.
By allowing the subclasses to fill in some operations in the different parts of the algo-
rithm, the design pattern allows for both the advantages of inheritance and the flexi-
bility of composition. Essentially the Template Method uses inheritance to vary parts
of the algorithm. Because the operations allow the subclasses to fill in their details,
think of the operations asplaceholdersawaiting details from the subclasses. By selec-
tively overriding the algorithm’s (template method’s) operations, each subclass can
get the functionality it needs.
The inverted control structure is sometimes called theHollywood Principlebecause
the parent classes in effect declare, “Don’t call us, we’ll call you,” to the child classes
(subclasses). This makes the general domain as defined in the abstract class the epi-
center. The parent class calls the operations of a subclass through the template