Categories
patterns

Pattern Patter: “Template Method” in Java

Summary: How to use the “Template Method” in Java frameworks.

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:

    setup();
    while (hasMore() {
        process();
    }
    teardown();

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:
    doSetup();
    while (hasMore()) {
        doProcess();
    }
    doTeardown();

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.

Result

Here’s the final version of our class:
    abstract public class TemplateMethodDemo {
        final public void process() {
            doSetup();
            while (hasMore()) {
                doProcess();
            }
            doTeardown();
        }
        protected void doSetup() {}
        protected void doTeardown() {}

        abstract protected boolean hasMore();
        abstract protected void doProcess();
    }
Here’s a sample subclass:

public class Test extends TemplateMethodDemo {
    int i = 0;
    protected boolean hasMore() {return i < 5;}
    protected void doProcess() {System.out.println(i++);}
    public static void main (String[] args) {
        TemplateMethodDemo t = new Test();
        t.process();
    }
}

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