Example of Template Method Design Pattern in Java

Problem Statement:

Let’s assume we are developing a game that involves different characters (e.g., warriors, mages, archers) that have a common sequence of actions during their turn in a battle. However, each character may have specific behavior for certain actions like attacking, defending, and resting.

Explanation of the Problem:

So in this problem, the ‘Character’ class is the abstract class that defines the template method ‘takeTurn()’. The concrete subclasses (‘Warrior’ and ‘Mage’) implement the abstract methods (‘startTurn()’, ‘performAction()’, ‘endTurn()’) according to their specific behaviors. The client code (‘Game’ class) can create instances of different characters and invoke their ‘takeTurn()’ method, relying on the template method to ensure a common sequence of actions.

Overall Code of above problem Statement:

Java




// Abstract class representing the character
abstract class Character {
     
    // Template method that defines the common sequence of actions
    public void takeTurn() {
        startTurn();
        performAction();
        endTurn();
    }
     
    // Abstract methods to be implemented by subclasses
    protected abstract void startTurn();
     
    protected abstract void performAction();
     
    protected abstract void endTurn();
}
 
// Concrete subclass representing a warrior character
class Warrior extends Character {
     
    @Override
    protected void startTurn() {
        System.out.println("Warrior is preparing for the turn.");
    }
 
    @Override
    protected void performAction() {
        System.out.println("Warrior is attacking with a sword.");
    }
 
    @Override
    protected void endTurn() {
        System.out.println("Warrior is resting after the turn.");
    }
}
 
// Concrete subclass representing a mage character
class Mage extends Character {
     
    @Override
    protected void startTurn() {
        System.out.println("Mage is focusing energy for the turn.");
    }
 
    @Override
    protected void performAction() {
        System.out.println("Mage is casting a spell.");
    }
 
    @Override
    protected void endTurn() {
        System.out.println("Mage is recovering after the turn.");
    }
}
 
// Client code
public class Game {
    public static void main(String[] args) {
        // Creating instances of different characters
        Character warrior = new Warrior();
        Character mage = new Mage();
         
        // Invoking the template method for each character
        System.out.println("Warrior's Turn:");
        warrior.takeTurn();
         
        System.out.println("\nMage's Turn:");
        mage.takeTurn();
    }
}


Output

Warrior's Turn:
Warrior is preparing for the turn.
Warrior is attacking with a sword.
Warrior is resting after the turn.

Mage's Turn:
Mage is focusing energy for the turn.
Mage is casting a spell.
Ma...

Diagrammatic Representation of Above Problem

Working of Template Method pattern

Abstract Character Class

Java




abstract class Character {
     
    // Template method that defines the common sequence of actions
    public void takeTurn() {
        startTurn();
        performAction();
        endTurn();
    }
     
    // Abstract methods to be implemented by subclasses
    protected abstract void startTurn();
     
    protected abstract void performAction();
     
    protected abstract void endTurn();
}


  • ‘Character’ is an abstract class representing the common structure of characters in the game.
  • ‘takeTurn()’ is the template method that defines the sequence of actions during a character’s turn. It consists of three steps: ‘startTurn()’, ‘performAction()’, and ‘endTurn()’.
  • There are three abstract methods (‘startTurn()’, ‘performAction()’, ‘endTurn()’) that subclasses must implement. These represent the specific actions that can vary for each type of character.

Concrete Warrior Class

Java




class Warrior extends Character {
     
    @Override
    protected void startTurn() {
        System.out.println("Warrior is preparing for the turn.");
    }
 
    @Override
    protected void performAction() {
        System.out.println("Warrior is attacking with a sword.");
    }
 
    @Override
    protected void endTurn() {
        System.out.println("Warrior is resting after the turn.");
    }
}


  • ‘Warrior’ is a concrete subclass of ‘Character’.
  • It overrides the abstract methods (‘startTurn()’, ‘performAction()’, ‘endTurn()’) with specific implementations for a warrior character.

Concrete Mage Class

Java




class Mage extends Character {
     
    @Override
    protected void startTurn() {
        System.out.println("Mage is focusing energy for the turn.");
    }
 
    @Override
    protected void performAction() {
        System.out.println("Mage is casting a spell.");
    }
 
    @Override
    protected void endTurn() {
        System.out.println("Mage is recovering after the turn.");
    }
}


  • ‘Mage’ is another concrete subclass of ‘Character’.
  • Similar to ‘Warrior’, it provides specific implementations for the abstract methods.

Client Code (Game Class)

Java




public class Game {
    public static void main(String[] args) {
        // Creating instances of different characters
        Character warrior = new Warrior();
        Character mage = new Mage();
         
        // Invoking the template method for each character
        System.out.println("Warrior's Turn:");
        warrior.takeTurn();
         
        System.out.println("\nMage's Turn:");
        mage.takeTurn();
    }
}


  • In the ‘Game’ class, instances of ‘Warrior’ and ‘Mage’ are created.
  • The ‘takeTurn()’ method is invoked for each character, demonstrating the template method pattern. The common sequence of actions (‘startTurn()’, ‘performAction()’, ‘endTurn()’) is followed, but the specific implementations for each character are called based on polymorphism.

Use Cases of Template Method Design Pattern in Java

This pattern is quite useful in scenarios where we have a common algorithm that needs slight variations in its steps based on different contexts. let’s see some of the common use cases of the Template Method Pattern:

  • Order of Operations: In the workflow system, we might have a template method that represents the overall process of handling a request. Subclasses can then override specific steps like validation, authorization, and execution while keeping the order of operations intact.
  • Code Reuse: In GUI frameworks, we could have a template method that outlines the process of rendering a UI component. Subclasses can then specialize in rendering specific types of components (e.g., buttons, text fields) while inheriting common behavior.
  • Database Access: In a database access library, we have the template method that represents the process of connecting to a database, executing a query, and closing the connection. Subclasses can provide specific implementations for different database systems.
  • Game Development: In the game development, a template method can define the overall game loop structure. Subclasses can then override specific steps like updating game logic, rendering graphics, and handling user input.
  • Logging Frameworks: In a logging framework, we have a template method that defines the process of logging information. Subclasses can provide specific implementations for logging to different destinations (e.g., console, file, database).
  • Document Generation: In a document generation system, we can use the template method for creating different types of documents (e.g., PDF, HTML). Subclasses can override steps like content generation and formatting while inheriting common document creation logic.
  • Web Frameworks: In a web framework, a template method can define the structure of handling HTTP requests. Subclasses can then provide specific implementations for routing, authentication, and request handling.
  • Workflow Engines: In the workflow engine, we might use a template method that represents the overall process of executing a workflow. Subclasses can specialize in implementing the specific activities or tasks within the workflow.

Template Method Design Pattern in Java

Template Design Pattern or Template Method is the behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.

This pattern falls under the category of the “behavioral” design patterns as it is concerned with how classes collaborate and communicate with other classes.

Important Topics for Template Method Design Pattern in Java

  • Key Component of Template Method Design Pattern
  • Example of Template Method Design Pattern in Java
  • Advantages of Template Method Design Pattern in Java
  • Disadvantages of Template Method Design Patten in Java

Similar Reads

Key Component of Template Method Design Pattern

In Java, the Template Method pattern is implemented using abstract classes. Let’s see the key elements of the Template Method Pattern:...

Example of Template Method Design Pattern in Java

Problem Statement:...

Advantages of Template Method Design Pattern in Java

...

Disadvantages of Template Method Design Patten in Java

...