GofPatterns Gofpatterns





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.
Template Pattern containing templateMethod() in the AbstractClass.


Benefits:
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
Diagram of the Template Pattern consisting of AbstractClass and ConcreteClass