Design Patterns
October 31, 2020

Theory: Template method

Design problem

Template Method is a behavioral pattern that describes the common algorithm while subclasses implement steps of this algorithm. This pattern lets the subclasses implement the steps of the algorithm without changing that algorithm's skeleton.

As an example of the Template Method, we will consider the working process. The algorithm contains three steps: go to work, work, go home. It's a very true-to-life example indeed.

Suppose all workers go to work and go home in an absolutely identical manner. The working routine, however, is different and depends on the worker’s qualification. We can choose any profession, but the algorithm remains the same.

Template method pattern

An abstract base class implements standard algorithm steps and can provide a default implementation for custom steps. Specific subclasses provide concrete implementation for each of these steps.

Template Method has the following components:

  • Abstract Class describes primitive operations and the template method itself which calls primitive operations;
  • Concrete Class implements the primitive operations.

Practice example

To demonstrate how the Template Method works, let's create an abstract class Worker that describes the working routine. Then, let's add the template method:

The common algorithm of actions is already determined. Now, we will create two concrete classes: Programmerand Actor:

In the Demo class we create programmer and actor instances and call the template method :


Template Method is applicable in the following cases:

  • When the behavior of an algorithm can vary, you let subclasses implement the behavior through overriding;
  • When you want to avoid code duplication, implementing variations of the algorithm in subclasses;
  • When you want to be sure that subclassing is allowed.