Applied Design Patterns with Java

Behavioral :: Template Method (325) {C ch 25}


Collaborations

Consequences

The Template Methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes.

Template Methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle" that is, "Don't call us, we'll call you". This refers to how a parent class calls the operations of a subclass and not the other way around.

Template Methods call the following kinds of operations:

  1. concrete operations (either on the ConcreteClass or on client classes);
  2. concrete AbstractClass operations (i.e., operations that are generally useful to subclasses);
  3. primitive operations (i.e., abstract operations);
  4. Factory Methods;
  5. hook operations, which provide default behavior that subclasses can extend if necessary. A hook operation often does nothing by default.

It's important for Template Methods to specify which operations are hooks (may be overridden) and which are abstract operations (must be overridden). To reuse an abstract class effectively, subclass writers must understand which operations are designed for overriding.

A subclass can extend a parent class operation's behavior by overriding the operation and calling the parent operation explicitly. Unfortunately, it's easy to forget to call the inherited operation. Transform such an operation into a
Template Method to give the parent control over how subclasses extend it. The idea is to call a hook operation from a Template Method in the parent class. Then subclasses can then override this hook operation, so the hook method does nothing in the parent class. Subclasses override the hook method to extend its behavior.

Catalog Behavioral Prev Next