Behavioral Patterns  «Prev  Next»

Template Pattern

The Template Method pattern provides a method that allows subclasses to override parts of the method without rewriting it. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the structure of the algorithm.
The figure below illustrates the Template pattern.

Template Pattern containing templateMethod() in the AbstractClass.


The following lists the benefits of using the Template pattern:
  1. Fundamental technique for reusing code

When to Use:

You should use the Template pattern when:
  1. You want to implement the invariant parts of an algorithm once and use subclasses to implement the behavior that can vary.
  2. When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.

Diagram of the Template Pattern consisting of AbstractClass and ConcreteClass

When there is an algorithm that could be implemented in multiple ways, the template pattern enables keeping the outline of the algorithm in a separate method (Template Method) inside a class (Template Class), leaving out the specific implementations of this algorithm to different subclasses. In other words, the Template Method pattern is used to keep the invariant part of the functionality in one place and allow the subclasses to provide the implementation of the variant part.