previous up next Template Method

Intent, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Sample Code, Known Uses, Related Patterns

previous next Consequences

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:
void DerivedClass::Operation () { // DerivedClass extended behavior ParentClass::Operation(); }
Unfortunately, it's easy to forget to call the inherited operation. We can 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:
void ParentClass::Operation () { // ParentClass behavior HookOperation(); }
HookOperation does nothing in ParentClass:
void ParentClass::HookOperation () { }
Subclasses override HookOperation to extends its behavior:
void DerivedClass::HookOperation () { // derived class extension }


Consequences of Abstract Factory, Adapter, Bridge, Builder, Chain of Responsibility, Command, Composite, Decorator, Facade, Factory Method, Flyweight, Interpreter, Iterator, Mediator, Memento, Observer, Prototype, Proxy, Singleton, State, Strategy, Template Method, Visitor

previous next