Template Method Pattern


Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.

Break down an algorithm into a series of steps, turn these steps into methods, and put a series of calls to these methods inside a template method. The steps may either be abstract, or have some default implementation.


Example

Coffee recipe:

  1. Boil water
  2. Brew coffee in water
  3. Pour coffee in cup
  4. Add sugar and milk
Tea recipe:
  1. Boil water
  2. Steep tea in water
  3. Pour tea in cup
  4. Add lemon

Hooks

There are different types of steps that can be used in the template method.
  • Abstract steps must be implemented by every subclass
  • Optional steps already have some default implementation, but still can be overridden if needed
  • Hook is an optional step with an empty or default implementation . If the subclasses want to use the hook, they just have to override it.

For example, different beverages have different sorts of possible condiments, but most beverages don't need any condiments. So we might want to make the addCondiments() a hook.

public abstract class Beverage {
    //Prevent subclasses from changing the algorithm
    //by declaring it as final
    final void prepareRecipe() {
        boilWater();
        pourInCup();
        brew();
        if (wantsCondiments()) {
            addCondiments();
        } 
    }

    //Optional steps
    void boilWater() { System.out.println("Boiling water"); }
    void pourInCup() { System.out.println("Pouring in cup"); }
    //Abstract method - every subclass has to implement it
    abstract void brew();
    abstract void addCondiments();
    //Hook method
    boolean wantsCondiments() {
        return true;
    }
}

Now we can introduce a beverage with no condiments without needing to override the addCondiments( ) method.

Design principles (link):

  • (NOK) You might violate the Liskov Substitution Principle by suppressing a default step implementation via a subclass.

Relations with Other Patterns

  • Template Method is based on inheritance: it lets you alter parts of an algorithm by extending those parts in subclasses. Strategy is based on composition: you can alter parts of the object’s behavior by supplying it with different strategies that correspond to that behavior. Template Method works at the class level, so it’s static. Strategy works on the object level, letting you switch behaviors at runtime.

Comments

Popular Posts