ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Key OOP Concepts Used with the Template Method | 335

The Template Method design pattern is simple to understand and apply. However,


as you’ll see, it has a number of features that make it unique. The real trick to using


the Template Method is knowing how to differentiate between the abstract func-


tions that must be overridden, concrete functions used consistently throughout the


algorithms that aren’t overridden, and those operations that act as hooks and are


optionally overridden. Throughout the examples, you’ll see more precisely how to


do this.


Key OOP Concepts Used with the Template Method


As one of only two design patterns that use inheritance instead of composition in the


Behavioral category of design patterns, the Template Method would seem to be a


hard sell when it comes to proposing the design pattern as a paragon of good OOP.


After all, the second principle put forth by GoF is tofavor composition over inherit-


ance. Why even bother with a design pattern that seems to favor inheritance over


composition? Further, is theHollywood Principleunique to the design patterns using


inheritance, or is it a general principle usable in both design patterns using composi-


tion as well?


Why Inheritance and Not Composition?


Whenever a design pattern uses inheritance as a key element instead of composition,


you need to consider the reason. To understand the reason, you need to fully under-


stand the principle of favoring composition over inheritance as a general principle in


good OOP. The principle’s established because of certain advantages of composi-


tion over inheritance, especially the composition advantage of not breaking encapsu-


lation. However, Gamma, Helm, Johnson and Vlissides (GoF) note that inheritance


also has certain advantages. One such advantage is that when using subclasses where


some but not alloperations are overridden, modifying the reused implementation is


easier. Because the Template Method design pattern does exactly that—uses some


but not all operations that can be overridden to achieve flexibility—it incorporates a


key advantage of inheritance over composition.


Figure 9-2. Template Method


AbstractClass
TemplateMethod()
PrimitiveOperationA()
PrimitiveOperationB()

ConcreteClass
PrimitiveOperationA()
PrimitiveOperationB()

PrimitiveOperationA()
PrimitiveOperationB()
Free download pdf