ActionScript 3.0 Design Patterns

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

Consider Variation


When selecting a design pattern, developers are advised toconsider what should vary


in a design. Here the emphasis changes from fretting over what causes redesign to


considering what you want to change. In the Template Method design pattern,the


template method encapsulates the different parts that go into the main algorithm. Each


abstract operation in the template method varies in the context of the algorithm.


Because the function’s locked, the sequence of operations doesn’t change, but the


operations themselves do. Hence, the design pattern principle ofencapsulating what


variesis nicely illustrated in the Template Method design pattern.


The Hollywood Principle


The casting director tells the actors who have tried out for a part, “We’ll let you


know, but don’t call us. We’ll call you.” The Template Method design pattern mir-


rors this: the template method itself is in the parent class, and the parent class calls


the subclasses. More specifically, the template method can call 1) concrete opera-


tions, 2) concrete operations from the main abstract class (where the template


method is defined), 3) primitive operations, 4) factory method (see Chapter 2), and



  1. hooks. However, these lower level objects cannot call the parent classes.


Because the GoF discuss only the Hollywood Principle in their Template Method


chapter, we considered whether this “principle” applies to all design patterns or just


certain ones with inverted control structures. If you go back to Chapter 2 and look at


the Factory Method, and Chapter 8 on the Observer pattern, you will see the princi-


ple at work as well. For example, the inverted control structure in the Observer pat-


tern informs all the relevant state changes to the subscribing objects. The


information flows from the top down to the lower level objects.


So, what’s the purpose of the principle? What does it do for reusable code? Eric and


Elisabeth Freeman summed it up nicely as a way to preventdependency rot. In other


words, it reduces the dependencies of higher-level components on lower-level com-


ponents and all their related dependencies. That’s a good thing because your system


is clearer to work with and understand. Figure 9-3 illustrates this principle.

Free download pdf