356 | Chapter 9: Template Method Pattern
Open a new Flash document, and typeTestFlightinto the document class window.
You should see the following results:
*^* Clear as a Bell *^*
Doing the walk around...looking good.
I'm off to Baja on a beautiful day!
First I'll file a VFR flightplan
*^* Cloudy *^*
Doing the walk around...looking good
In the first part, you can see that both of the algorithm’s operations successfully out-
put thecheckAirplane( )andfileVFR( )method results. However, in theCloudy
instance, only thecheckAirplane( )method invokes. This is as expected because in
theCloudyclass, thecheckWeather( )hook method returned something other than
“Nice and clear,” thereby canceling thefileVFR( ) operation.
Summary
The Template Method design pattern shows how to distribute behavior among sub-
classes. It leaves much of the detail work to the subclasses, but at the same time it
can control the order of the algorithm making up the template method. It stands as a
good example of controlling dependencies and use of the inverted control structure.
As such, the Template Method has many uses where both control and flexibility are
required while minimizing dependency. It is a widely used pattern, and in many
abstract classes you can find some a template method at work to some degree. It’s
truly a general pattern because it offers both algorithm control and subclass flexibil-
ity in implementing the class methods.
The Template Method in ActionScript 3.0 is quite useful even though the language
lacks abstract functions and classes. By treating the default internal functions with
no content as though they are abstract operations, it’s possible to use template meth-
ods that are virtually identical to languages that feature both abstract classes and
functions.
Finally, hook methods offer further flexibility without really disrupting the main
algorithm’s flow. These methods can act like “back doors” to the main algorithm. All
the operations in the template methods stay in the same order, but they can be
changed in terms of what they do, or if they’re omitted in the invocation of the tem-
plate method. It’s little wonder that the Template Method, with its strong structure
and flexible implementation, is so widely used.