Template Method

Get an overview of the template design pattern.

Let’s take a top-down approach to understand this design pattern.

Definition

A template method is a behavioral design pattern. It’s used to create a method in the parent class and defer some of the implementation steps to the subclasses.

Explanation

According to the definition above, we would have a parent class containing the template method. In this method, we would have two types of operations:

  • Operation(s) that are the same for all of its child classes.
  • Operation(s) that are different for the subclasses.

Let’s look at an example machine learning model. Suppose that there’s the parent class of the machine learning model. Many classes can inherit this class, such as linear regression, artificial neural network, random forest, and so on. Regardless of the model being used, a machine learning application would follow the following general steps:

  • Read the data from a file
  • Train a model
  • Write forecast data to a file

The only difference would be the training model being used.

The template method defines the skeleton of operations in an abstract class. Some of these steps will be implemented in the parent class and the rest in the subclasses. Through the template method, we can avoid code duplication. In our example, without a template method, we would need to write read and write methods for every model, but with the template method, we only write it once.

The key points to remember while implementing the template methods are:

  • The sequence of the substeps of an algorithm is always the same.
  • Subclasses can adapt individual substeps.

Type

The template method is an object-oriented programming pattern in the behavioral design patterns category.

Applicability

We can use the template method when different algorithms have some common code but differ in some steps. By using the template method, we can avoid code duplication.

Structure

Get hands-on with 1200+ tech skills courses.