Skip to content

Template Method

Roberto Fronteddu edited this page Jan 25, 2023 · 1 revision

The Template Method is a Behavioral Design Pattern. It works by allowing the definition of a method as a series of steps (method calls) and provides a chance for subclasses to define or redefine some of these steps. The pattern works by defining abstract methods which then have to be implemented by concrete subclasses. These methods are like hooks which are then called by the Template Method.

Usefull when

  • You need to defer the implementation of parts of your algorithm which can vary or change.

UML

template uml

  • AbstractClass: Implements the template method using one or more abstract steps. Each step is an abstract method.
  • ConcreteClassA/B: Implement the individual steps which are called by the template method.

Implementation steps

  1. Define the template method. Try to break the algorithm into multiple steps where each step will become an abstract method.
  2. Implement the abstract steps in one or more subclasses

Design considerations

  • The Template Method is an example of the inversion of control principle (don't call us, we will call you).
  • Too many steps mean too many methods to override, and too few mean that the subclasses end up defining major parts of the algorithm.
  • If the template method is final, it cannot be re-defined by subclasses.
  • We can use subclasses and inheritance to reimplement only certain steps.
  • Factory Method is often called as one of the steps of the Template Method

Comparison with Strategy

Template Method

  • All subclasses implement the steps for the same algorithm.
  • Client code relies solely on inheritance to get a variation of the same algorithm

Strategy

  • Each subclass represents a separate algorithm
  • Client code uses composition to configure the main class with the chosen strategy.

Pitfalls

  • Tracking code may require looking up multiple classes.
  • Unit testing can become very complicated since they may require some specific state

Real-Life Examples

  • java.util.AbstractMap and AbstractSet have many non-abstract methods that are good examples of template method.
Clone this wiki locally