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:
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.