Template Design Pattern in Java

Template Method Design Pattern in Java with Examples

In this article, I am going to discuss the Template Method Design Pattern in Java with Examples. Please read our previous article where we discussed the Strategy Design Pattern in Java with Examples. The Template Design Pattern falls under the category of Behavioral Design Pattern. In this article, we will explore the Template Method Design Pattern, its advantages, disadvantages, and its effective utilization in software development.

What is Template Design Pattern?

According to Gang of Four, Template Method Design Pattern defines a sequence of steps of an algorithm and allows the subclasses to override the steps but is not allowed to change the sequence

In the realm of software development, creating modular and reusable code is vital for building scalable and maintainable systems. One design pattern that aids in achieving these goals is the Template Design Pattern. The Template Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to override specific steps of the algorithm.

The Template Method Design Pattern revolves around the concept of defining an algorithm’s structure in a base class, known as the template class. The template class provides a default implementation of the algorithm by breaking it down into several steps or methods. These methods are designed to be overridden by the subclasses, enabling them to provide their own specialized implementations for specific steps. The template class then orchestrates the overall algorithm by invoking these methods in a defined sequence.

Real-Time Example to Understand Template Method Design Pattern:

Suppose you want to prepare Coffee (let’s say BruCoffee). Then you need to follow some steps or procedures such as Boil Water, Add Milk, Add Sugar, and Adding BruCoffee which is shown in the following image.

Real-Time Example to Understand Template Method Design Pattern

Suppose you want to prepare Nescafe Coffee. Then also you need to follow the same procedure as BruCofee such as Boil Water, Add Milk, Add Sugar, and Add Nescafe Coffee as shown in the following image.

Real-Time Example to Understand Template Method Design Pattern

If you see both the coffee preparation procedure, it is almost the same i.e. Boil Water, Add Milk, Add Sugar, Add Coffee type (i.e. Bru and Nescafe), and based on the Coffee type, it will create either Bru Coffee or Nescafe Coffee. So, the procedure for creating coffee is the same. What I can do here is, I can create a template method (let us say PrepareCoffee) and within that PrepareCoffee template method, I can define the procedure to create the coffee. For a better understanding please have a look at the following diagram.

Real-Time Example to Understand Template Method Design Pattern

Implementing Template Method Design Pattern in Java:

Consider a multiplex that shows two types of movies: Hollywood and Bollywood. We create an abstract class called Movie which defines the basic functions of both types of movies. Then, we create a demo class that simulates the program. The UML Diagram of this example is given below using Template Design Pattern.

Implementing Template Method Design Pattern in Java

Step 1: Create a new directory to store all the class files of this project.

Step 2: Open VS Code and create a new project, called template.

Step 3: In the project, create a new file called Movie.java. Add the following code to the file:

public abstract class Movie
{
    public abstract void displayAds();
    public abstract void start();
    public abstract void interval();
    public abstract void endCredits();
    
    public final void watchMovie()
    {
        displayAds();
        start();
        interval();
        endCredits();
    }
}

This is the abstract class from which other concrete classes will extend.

Step 4: In the project, create two new files called HollywoodMovie.java and BollywoodMovie.java. Both of these files extend from the Movie interface. Add the following code to the files:

BollywoodMovie.java
public class BollywoodMovie extends Movie
{
    @Override
    public void displayAds()
    {System.out.println("Before bollywood movie: Displaying pan masala ad now.");}

    @Override
    public void start()
    {System.out.println("Bollywood movie is starting! Turn down the lights!");}

    @Override
    public void interval()
    {System.out.println("Bollywood movie interval!");}

    @Override
    public void endCredits()
    {System.out.println("Bollywood movie is ending! Turn on the lights!");}
}
HollywoodMovie.java
public class HollywoodMovie extends Movie
{
    @Override
    public void displayAds()
    {System.out.println("Before hollywood movie: Displaying pan masala ad now.");}

    @Override
    public void start()
    {System.out.println("Hollywood movie is starting! Turn down the lights!");}

    @Override
    public void interval()
    {System.out.println("Hollywood movie interval!");}

    @Override
    public void endCredits()
    {System.out.println("Hollywood movie is ending! Turn on the lights!");}
}

Step 5: In the project, create a new file called TemplatePatternDemo.java. This class will contain the main() function. Add the following code to TemplatePatternDemo.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TemplatePatternDemo
{
    public static void main(String[] args) throws NumberFormatException, IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter 1 for hollywood and 2 for bollywood: ");
        int choice = Integer.parseInt(br.readLine());

        if (choice == 1)
            new HollywoodMovie().watchMovie();
        else if (choice == 2)
            new BollywoodMovie().watchMovie();
        else
            System.out.println("Invalid choice!");
    }
}

This main() function asks the user which movie they would like to watch. Once the user enters their choice, the movie will be “shown”.

Step 6: Compile and execute the application. Ensure compilation is successful. Verify that the program works as expected.

Template Method Design Pattern in Java with Examples

Congratulations! You now know how to implement template patterns!

UML Diagram of Template Method Design Pattern:

Now, let us see the Template Design Pattern UML Diagram Components with our Example so that you can easily understand the UML Diagram.

UML Diagram of Template Method Design Pattern

The classes can be described as follows:

  1. Object: This is the interface that will define the basic methods that will be implemented by the concrete object class.
  2. ConcreteObject: This class implements the Object interface. It implements the functions defined in the interface.
  3. DriverClass: This class contains the main() function and is responsible for the simulation of the program.
Advantages of Template Method Design Pattern in Java

The advantages of using the Template Method Design Pattern in Java are as follows:

  • Code Reusability: The Template Design Pattern promotes code reuse by providing a generic algorithm structure in the template class. The common code and the overall flow of the algorithm are centralized in one place, reducing duplication and enhancing maintainability. The subclasses only need to focus on implementing the specific steps that vary, resulting in cleaner and more concise code.
  • Structure and Consistency: By defining the overall algorithm structure in the template class, the Template Design Pattern ensures consistency across different implementations. The template class enforces a standardized sequence of method invocations, guaranteeing that each subclass adheres to the same underlying algorithmic flow. This consistency improves code readability, and maintainability, and reduces the likelihood of errors caused by variations in implementation.
  • Flexibility and Customization: The Template Design Pattern allows subclasses to customize specific steps of the algorithm while keeping the overall structure intact. This flexibility enables developers to tailor the behavior of the algorithm to specific requirements or variations. For example, in a data import process, different subclasses can override the data validation or transformation steps based on the specific file formats being processed.
  • Simplified Maintenance: The Template Design Pattern simplifies maintenance by isolating changes to specific steps within the subclasses. If a modification is required, developers can focus on the relevant subclass without affecting other parts of the system. This modular approach improves code maintainability, reduces the risk of introducing bugs, and facilitates easier troubleshooting and debugging.
  • Encapsulation and Separation of Concerns: The Template Design Pattern promotes the separation of concerns by encapsulating common algorithmic logic in the template class. Each subclass is responsible for its own specialized behavior, which enhances code readability and maintainability. This separation of concerns also allows for easy unit testing, as the template class can be tested separately from the subclasses.
Disadvantages of Template Method Design Pattern in Java

The disadvantages of using the Template Method Design Pattern in Java are as follows:

  • Inflexibility in Algorithm Modifications: The Template Design Pattern may become a hindrance if substantial modifications are required to the overall algorithm structure. As the template class defines the high-level structure, altering it can be challenging without affecting the existing subclasses. If significant changes are needed, developers may need to introduce a new template class or consider a different design pattern altogether.
  • Limited Runtime Flexibility: Since the template class defines the algorithm structure at compile-time, it offers limited flexibility during runtime. The decision of which subclass to use is typically made during instantiation, and cannot be easily changed dynamically. This lack of runtime flexibility may restrict the adaptability of the algorithm to dynamic or evolving scenarios.
  • Increased Complexity: The Template Design Pattern can introduce additional complexity to the codebase, particularly when dealing with complex algorithms or a large number of subclasses. Understanding the flow of the algorithm and the interactions between the template class and subclasses can become
  • Challenging: Especially for developers new to the codebase, it could be challenging to use this pattern. Care must be taken to strike a balance between code reusability and the potential complexity introduced by the pattern.
  • Tight Coupling with the Template Class: Subclasses in the Template Design Pattern are tightly coupled to the template class. Any changes made to the template class, such as the addition or modification of methods, can impact the subclasses. This tight coupling can make it more challenging to maintain and evolve the codebase, as changes in one part of the system may require modifications in multiple subclasses.

In the next article, I am going to discuss Null Object Design Pattern in Java with Examples. Here, in this article, I try to explain Template Method Design Pattern in Java with Examples. I hope you understood the need for and use of the Template Method Design Pattern in Java.

1 thought on “Template Design Pattern in Java”

Leave a Reply

Your email address will not be published. Required fields are marked *