top of page

Template Method Design Pattern

Updated: Apr 4, 2023

Template Method Design Pattern is a software design pattern that provides a way to define the skeleton of an algorithm in a base class while allowing subclasses to override specific steps of the algorithm without changing its structure.


In simpler words, Template Method is a pattern that allows you to create a blueprint for a certain process, where the general steps are defined in a base class, while the specific steps can be customized in derived classes.


The pattern is useful when you want to create a process that can be broken down into multiple steps, but the overall structure of the process remains the same. By using a Template Method, you can avoid duplicating code across different classes, and instead define the general structure of the process once in a base class, and then customize it in the subclasses.


UML Class Diagram




Implementation Steps

The Template Method Design Pattern can be implemented in the following steps:

  1. Identify the algorithm: Identify the algorithm that you want to define as a template. The algorithm should have a well-defined structure but with some variable steps that can be customized.

  2. Define the abstract base class: Create an abstract base class that defines the overall structure of the algorithm. This base class should define the template method that calls the algorithm's steps in the correct order.

  3. Define the variable steps: Define the variable steps of the algorithm as abstract methods in the base class. These methods will be implemented by the subclasses to customize the algorithm's behavior.

  4. Define the concrete subclasses: Create concrete subclasses that inherit from the base class and implement the abstract methods to provide specific behavior for the variable steps.

  5. Implement the template method: Implement the template method in the base class, which will call the algorithm's steps in the correct order, including the abstract methods defined in the subclasses.

  6. Call the template method: Call the template method from the client code to execute the algorithm. The template method will call the algorithm's steps in the correct order, using the concrete implementations of the variable steps defined in the subclasses.

  7. Optional: Provide hooks for customization: If needed, provide hooks in the base class to allow subclasses to customize other aspects of the algorithm's behavior.


Source Code Implementation


Step 1: Identify the algorithm that needs to be standardized

The first step in implementing the Template Method Design Pattern is to identify the algorithm that needs to be standardized. This algorithm should have a well-defined structure but with some variable steps that can be customized by subclasses.


For example, let's say we want to create a simple algorithm for making a cup of tea. The steps involved in making tea are generally the same, but the specific details of each step may vary depending on the type of tea being made or personal preferences.


Step 2: Create an abstract base class

The next step is to create an abstract base class that defines the generic algorithm and declares abstract methods for the variable steps that can be customized by subclasses. This base class serves as a blueprint for the algorithm and provides a common interface for all subclasses.


Here's an example code:

from abc import ABC, abstractmethod

class HotBeverage(ABC):
    def prepare(self):
        self.boil_water()
        self.steep()
        self.pour()
        self.add_condiments()

    def boil_water(self):
        print("Boiling water...")

    @abstractmethoddef steep(self):
        passdef pour(self):
        print("Pouring hot water...")

    @abstractmethoddef add_condiments(self):
        pass

In this example, we have created an abstract base class HotBeverage that defines the generic algorithm for preparing a hot beverage. The prepare method is the template method that defines the overall structure of the algorithm, while the boil_water and pour methods are concrete methods that provide a default implementation. The steep and add_condiments methods are declared as abstract methods, which means that they must be implemented by the subclasses.


Step 3: Create concrete subclasses

The next step is to create concrete subclasses that implement the abstract methods declared in the base class. These subclasses customize the behavior of the algorithm by providing their own implementations for the variable steps.


Here's an example code for a concrete subclass Tea:

class Tea(HotBeverage):
    def steep(self):
        print("Steeping the tea...")

    def add_condiments(self):
        print("Adding lemon...")

In this example, we have created a concrete subclass Tea that implements the steep and add_condiments methods to customize the behavior of the algorithm for making tea.


Step 4: Use the template method

The final step is to use the template method to create and execute the algorithm. In this step, we create an instance of the concrete subclass and call the prepare method to execute the algorithm.


Here's an example code:

if __name__ == "__main__":
    tea = Tea()
    tea.prepare()

In this example, we have created an instance of the Tea class and called the prepare method to execute the algorithm for making tea.


When To Apply Template Method Design Pattern

The Template Method Design Pattern is a useful pattern to apply when you want to create a process or algorithm that has a well-defined structure but with some variable steps. Here are some scenarios where you may want to apply the Template Method pattern:

  1. When you have a process that can be broken down into multiple steps, the overall structure of the process remains the same.

  2. When you want to avoid code duplication across multiple classes, instead define the general structure of the process once in a base class.

  3. When you want to allow subclasses to customize specific steps of the algorithm without changing its structure.

  4. When you want to provide a way for clients to extend or modify the behavior of the algorithm at runtime.

  5. When you want to create a framework or library that provides a standard way of implementing a certain process but allows users to customize it to their specific needs.


Benefits of Template Method Design Pattern

The Template Method Design Pattern offers several benefits, including:

  1. Promotes code reuse by allowing you to define a generic algorithm in a base class and reuse it in different subclasses.

  2. Modular design by breaking down complex algorithms into smaller, more manageable steps.

  3. It allows subclasses to override specific steps of the algorithm without changing its overall structure, enabling greater customization of behavior.

  4. It provides a flexible way of defining algorithms that can be easily extended or modified by clients at runtime.

  5. Encapsulates the algorithm's logic in a single location, making it easier to maintain and modify.

  6. It promotes consistency in code design by providing a standard way of implementing a particular algorithm, making the code more readable and easier to understand.


The Tech Platform

0 comments

Recent Posts

See All
bottom of page