Template Method Design Pattern

What is Template Method Design Pattern?

  • It falls under behavioral design pattern.
  • It defines a sequence of steps of an algorithm.
  • Subclasses can override the steps but it won’t allow to alter the sequence of steps.
  • House building: basement, pillars, side walls, interior – concrete and wooden house
  • Software development: analysis, design, develop and test.

Real Life Examples of Template Method Design Pattern

Example 1:

house sample photoLet's suppose if you want to construct a house, and you need to follow several steps. You need to set up the basement; you need to construct the pillars, and you need to construct side walls and other steps. The house can be constructed using cement or wood, but you need to follow the above steps. So here the steps are common to construct any house. It can be a Concrete house, Wooden house, etc. So here the steps are the templates for any house construction.

Example 2:

software development sample photoLet's consider a software development process if you want to develop any software like baking software, stock market software, etc., and you need to follow the following steps. You need to analyze the software requirements, and you need to estimate the project budget and duration, and you need to design the software, and you need to develop the software. So here the steps are the templates for any software development.

UML Class Diagram of Template Method Design Pattern

Template Method Design Pattern Java Implementation

Step 1:

public class Voltage
{

    private int voltage;

    public Voltage(int v)
    {
        this.voltage = v;
    }

    public int getVolts()
    {
        return voltage;
    }

    public void setVolts(int voltage)
    {
        this.voltage = voltage;
    }

}

Tutorial Videos of Template Method Design Pattern

For tutorial videos, please check out the premium Software Design Pattern course on Udemy.