Template Method Design Pattern

Learn via video courses
Topics Covered

Abstract

The template method design pattern falls under the category of behavioral design pattern. It describes a technique (also known as an algorithm) that is in the form of a skeleton of functions. The child classes are responsible for implementing the specifics for this method. The parent class maintains the algorithm's basic framework as well as sequencing.

When will we need the template method design pattern?

Frameworks make extensive application of the Template Method Design Pattern. Every framework executes the immutable components of a domain's design as well as it creates placeholders for any essential or relevant user modification choices. As a result, the framework becomes the centre of the world, while the client modifications can be said as just the fourth rock from the sun in the sky.

template method design pattern The template methodology is adopted in frameworks, in which each applies the domain's immutable components while allowing "placeholders" for modification choices. For the reasons listed below, the template technique is used:

  • Template method design pattern allows subclasses to specify behavioural patterns which are achieved by using the concept of method overriding.
  • To prevent code duplication, the overall workflow structure is applied once in the algorithm of the abstract class, as well as any changes are applied in the subclasses.
  • Limit the points at which subclassing is permitted. Unlike a basic polymorphic override, in which the underlying function is completely rebuilt, enabling drastic changes to the workflow, just the specifics of the process are permitted to alter.
  • You can apply this pattern if the majority of given classes exhibit similar characteristics.

Real-Life Example

We'll discuss one real-life explanation to understand the concept of template method pattern in an easy way. Let's say Rahul needs to build a concrete building. To build a concrete house he has to go through the following steps:

  1. Foundation of the house
  2. Pillars of the house
  3. Walls
  4. Windows and Doors of the house

Rahul's friend Aryan wants to make a wooden house for his family. It's just that in the place of concrete Aryan will be using wood to construct his house. To build a concrete house he has to go through the following steps:

  1. Foundation of the house
  2. Pillars of the house
  3. Walls
  4. Windows and Doors of the house

In such a situation, we can design a template method named House Building which has all the basic four steps mentioned above. Here's what templates will look like: template method named House Building

With this template, any kind of house can be made. Therefore, the key to the Template method pattern is that we can put the basic logic in the abstract parent class and we can let the child class describe the specifications.

How does the template method design pattern work?

The Template Method specifies the skeleton of an algorithm in an operation while delegating some elements to subclasses. The template technique breaks down the algorithm into stages. The stages are applied in the abstract class, and the concrete steps, which differ between concrete classes, are implemented in the concrete class

Structure

In the Template method design pattern, there are two classes. Let's go through the structure of the design pattern.

  1. Abstract Class- The Abstract Class specifies functions that serve as algorithm stages, and the real template method that invokes these functions in a certain order. Steps might be specified abstract or have a default implementation.
  2. Concrete Class -Concrete Classes might override each and every step except the template method. structure of the design pattern

Implementation Details

Problem: Let's use an example to better grasp this pattern: Assume we intend to create an algorithm for the daily routine of workers.

Step by step

  1. Analyze the algorithm as well as determine which stages are common and which are unique to each of the present classes.
  2. The next step is to create a new abstract base class to hold the framework "don't call us, we'll call you."
  3. Transfer the algorithm's shell (now known as the "template method") as well as the declaration of every general stage to the new base class.
  4. In the basic class, the programmer defines a "hook" or placeholder method for every step that needs several implementations. This method can be specified as abstract ( in the programming language Java) or pure virtual in the programming language C++, or it can contain a default implementation.
  5. Now, from the template design method, call the hook method(s).
  6. Every existing class specifies a "is-a" connection with the new abstract base class.
  7. Eliminate all implementation details which have been relocated to the base class from the classes which already exist.
  8. The only features that would persist in the old classes are those specific to every derived class's implementation.

Pseudocode

In this example, the Template Method pattern provides a “skeleton” for various branches of artificial intelligence in a simple strategy video game. Pseudocode

Template Method Abstract Class - We want subclasses to implement some of the functions,  so we must make our base class abstract.

Template Method Concrete Class- We'll write the code for a teacher using the concept of template method design

Similarly, we can reuse the code for writing a program for the work routine of plumbers, doctors, and any other workers.

Pros and Cons of Template Method Design Pattern

Pros of template method design pattern-

  • This behavioural design pattern is among the simplest to grasp as well as apply.
  • The design pattern is generally utilized in the development of frameworks.
  • The code becomes much cleaner since it also aims to alleviate the duplication of code.

Cons of template method design pattern-

  • At times, it might be difficult to debug as well as comprehend the flow sequence in the Template method pattern design. There might be cases where the programmer might find themselves applying a function that should not be implemented or you might not implement a given abstract method at all. The programmer is responsible for documentation as well as stringent error handling.
  • It might be a difficult task to maintain the template framework since any kind of modifications in the lower or higher level might conflict with the implementation.

Difference between Template method pattern and Strategy pattern

Below are several aspects as well as perspectives on template method design patterns and Strategy patterns.

Template Method PatternStrategy Pattern
Template Method Patterns encapsulate algorithms using the concept of inheritance.Strategy Patterns encapsulate algorithms using the concept of composition.
Template Pattern is known to be more efficient than Strategy pattern.Strategy Patterns is more flexible as it uses the concept of object composition.
Template Method is used to modify individual phases in an algorithm.The Strategy Method is used to enable callers to change a complete algorithm.
Template Method PatternStrategy Pattern

Frequently Asked Questions

Question 1 - In Java, what is the Template Method pattern?
The Template Method is a behavioral design pattern that allows the programmer to specify an algorithm's skeleton in a base class and then let subclasses alter the steps without affecting the general structure of the algorithm.

Question 2 - When should you utilize a template method?
The template method is used under the following cases:

  • An interesting use case for this approach is when you have copied the code which is pasted (private functions) across various classes.
  • Finally, you can employ this strategy if the majority of your classes exhibit similar characteristics. To avoid code duplication, the overall structure of the process is applied once in the algorithm of the abstract class whereas any changes are applied in the subclasses.
  • To avoid code duplication, the overall structure of the process is applied once in the algorithm of the abstract class whereas any changes are applied in the subclasses.

Question 3 - How does the Template method work?
Let's know how does this works, An abstract class provides a described template(s) or way(s) to run its functions in the Template pattern. The subclasses of this abstract class can override the function implementation as required, but the function call must follow the rules provided by the given abstract class.