The Template Method is a pattern commonly used in frameworks to implement the "Hollywood Principle": "Don't call us, we'll call you." [Design Patterns, Gamma et al.]
The key idea is that there is a basic algorithm we want to stay the same, but we want to let subclasses vary how they do the steps. The Template Method says to define the algorithm in the parent class, but implementations of the steps in the subclasses. For example, let's take the most basic algorithm for processing a set of items:
The parent class doesn't know (or care) what setup()
involves - it just knows when to call it.
Issue 1: Naming
There is a convention for template methods: start action names
with "do". Our example might become:
Issue 2: Protection
The algorithm we've been discussing is in a public method; it's
intended to be called from outside. The steps of the algorithm
(doSetup() etc.) are protected. A subclass is expected to
override these methods with the real implementation.
Issue 3: Abstract Class
Another decision is whether the methods must be implemented by
the subclass, or whether the parent class can provide a default
implementation. Sometimes, it makes sense to do both (for different
methods). In our example, doSetup() and
doTeardown() might default to empty actions, but
hasMore() and doProcess() must be provided.
Declare required methods abstract (and mark the parent class
abstract as well).
Issue 4: Final Method
Since the main algorithm is intended to stay the same, we can
declare it final, to ensure that subclasses don't change it.
Here's the final version of our class:
protected boolean hasMore();
Here's a sample subclass:
For more information on the Template Method pattern, see the Design Patterns book (Gamma et al.), or the article "Protection, Part I: The Hollywood Principle", by John Vlissides, C++ Report, February, 1996, which explored this pattern and these ideas in C++.
[Written 6-1-99; example corrected 10-2-02 from feedback by Ilja Preuss, and 1-6-03 from Brook Everest.]
Copyright 1994-2010, William C. Wake - William.Wake@acm.org