The Wayback Machine - https://web.archive.org/web/20241001084253/https://www.geeksforgeeks.org/template-method-design-pattern-in-java/
Open In App

Template Method Design Pattern in Java

Last Updated : 06 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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:

Abstract Class

  • Define an abstract class that declares the template method. The template method typically consists of a series of method calls and control flow statements.
  • The template method defines the algorithm’s structure but leaves some steps to be implemented by concrete subclasses.

Concrete Classes

  • Create concrete subclasses that extend the abstract class.
  • Implement the abstract methods declared in the abstract class to provide specific behavior for each step of the algorithm.

Template Method Invocation

  • Clients use the template method to execute the algorithm. The template method ensures that the steps are executed in the correct order, and some steps may be overridden by subclasses.

Hooks

  • Hooks are methods in the superclass that have a default (empty or no-op) implementation but can be optionally overridden by subclasses. They allow subclasses to “hook into” the algorithm at certain points, influencing its behavior.

So this Pattern provides a way to define the skeleton of an algorithm in the superclass while allowing subclasses to provide specific implementations for certain steps. This promotes code reuse and ensures that the overall algorithm structure remains consistent across different implementations.

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

2023-11-26_8-21-41

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.

Advantages of Template Method Design Pattern in Java

Let’s see some of the advantages of Template Method Pattern:

  • Consistent Algorithm Structure: The pattern enforces a consistent algorithm structure across multiple subclasses. This ensures that certain steps are followed in a prescribed order, providing a common interface for different implementations.
  • Code Reusability: The pattern promotes code reuse by defining a common algorithm structure in the superclass. Subclasses can reuse this structure without duplicating code.
  • Maintenance and Extensibility: Changes to the algorithm can be made in the superclass, affecting all subclasses. This makes maintenance easier and allows for the extension of the algorithm without modifying existing code in the subclasses.
  • Enforcement of Steps: The Template Method Pattern enforces certain steps in the algorithm by defining them in the superclass. This can be useful in situations where certain steps must always be executed in a particular order.
  • Flexibility for Subclasses: Subclasses can provide their own implementations for specific steps of the algorithm without changing the overall structure. This allows for customization and specialization while adhering to a common framework.
  • Reduced Code Duplication: Since the common algorithm is defined in the superclass, there is less duplication of code across subclasses. This can lead to a more maintainable and less error-prone codebase.
  • Support for Hook Methods: Template methods often include “hook” methods, which are empty or default implementations in the superclass. Subclasses can choose to override these methods to add or modify behavior, providing additional points of customization.
  • Simplified Client Code: Clients using the template method interact with the algorithm through a common interface provided by the superclass. This simplifies client code by abstracting away the details of individual implementations in subclasses.

Disadvantages of Template Method Design Patten in Java

While the Template Method Pattern offers several advantages, it also has some potential disadvantages also:

  • Increased Complexity: As the number of steps and variations in the algorithm increases, the template method can become more complex. This may make it harder to understand and maintain, especially when dealing with a large number of subclasses and potential variations.
  • Inflexibility in Run-Time Changes: The template method defines the algorithm structure at compile time, making it less suitable for situations where the algorithm needs to change dynamically at runtime. If the steps of the algorithm need to be reconfigured during program execution, this pattern may not be the best choice.
  • Difficulty in Understanding the Flow: In some cases, it might be challenging to understand the flow of control within the template method, especially if there are many subclasses and overridden methods. This can impact code readability.
  • Overhead of Inheritance: The pattern relies heavily on inheritance, and using it excessively can lead to the “fragile base class” problem. Changes to the superclass can potentially affect all subclasses, and modifications to the template method might require changes in all derived classes.
  • Less Support for Code Composition: The Template Method Pattern is more focused on inheritance and may not be as suitable for scenarios where code composition is preferred over inheritance. This can limit the ability to mix and match behavior dynamically.
  • Limited Support for Multiple Inheritance: In languages that do not support multiple inheritance, the Template Method Pattern might be less flexible when it comes to incorporating behavior from multiple sources.
  • Potential for Violation of Liskov Substitution Principle: If subclasses override certain steps in a way that violates the Liskov Substitution Principle, it can lead to unexpected behavior and may break the assumptions made by the template method.
  • Limited Runtime Polymorphism: Since the structure of the algorithm is defined in the template method at compile time, there is limited support for runtime polymorphism. This may limit the ability to change algorithm behavior dynamically.


Previous Article
Next Article

Similar Reads

Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Template Method Design Pattern
The Template Method design pattern is a behavioral design pattern that defines the skeleton of an algorithm in a superclass but allows subclasses to override specific steps of the algorithm without changing its structure. It promotes code reuse by encapsulating the common algorithmic structure in the superclass while allowing subclasses to provide
8 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Curiously recurring template pattern (CRTP)
Background: It is recommended to refer Virtual Functions and Runtime Polymorphism as a prerequisite of this. Below is an example program to demonstrate run time polymorphism. C/C++ Code // A simple C++ program to demonstrate run-time // polymorphism #include <chrono> #include <iostream> using namespace std; typedef std::chrono::high_res
7 min read
Service Template Pattern in Microservices
The Service Template Pattern is a useful design approach in microservices that helps streamline service creation. In microservices architecture, different services often share similar logic, like handling requests, responses, or security. The Service Template Pattern provides a blueprint, or template, for these common tasks, reducing repetition and
15+ min read
Template Method | JavaScript Design Patterns
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure across different subclasses. Important Topics for
10 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with ma
8 min read
Proxy Method Design Pattern in Java
A Proxy Method or Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. This pattern involves creating a new class, known as the proxy, which acts as an intermediary between a client and the real object. The proxy object controls access to the real object, allowing y
9 min read
Strategy Method Design Pattern in Java
Strategy method or Strategy Design Pattern is a behavioral design pattern in Java that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It lets the client algorithm vary independently from the objects that use it. This pattern is useful when you have a family of algorithms and want to make them interchang
11 min read
Command Method Design Pattern in Java
The Command Design Pattern in Java is a behavioral design pattern that turns a request into a stand-alone object, allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations(action or a series of actions that can be reversed or undone in a system). Important Topics for Command Method Design
10 min read
Null Object Method Design Pattern in Java
The Null Object Design Pattern is a behavioral design pattern that is used to provide a consistent way of handling null or non-existing objects. It is particularly useful in situations where you want to avoid explicit null checks and provide a default behavior for objects that may not exist. Important Topics for Null Object Method Design Pattern in
10 min read
Facade Method Design Pattern in Java
Facade Method Design Pattern is a structural design pattern that provides a simplified interface to a complex subsystem. It acts as a "front door," concealing the internal complexity of the subsystem and making it easier for clients to interact with it. In this article, we will get to know about what is Facade Method Design Pattern in Java, and why
9 min read
Flyweight Method Design Pattern in Java
A flyweight design pattern or flyweight method is defined as a structural pattern that is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects. The key idea behind the Flyweight pattern is to use shared objects to support large numbers of fine-grained objects efficiently. Important Topics
9 min read
Observer Method Design Pattern in Java
Observer Design Pattern is a behavioral design pattern where an object, known as the subject, maintains a list of its dependents, called observers, that are notified of any changes in the subject's state. This pattern is often used to implement distributed event handling systems. Important Topics for Observer Method Design Pattern How We can implem
11 min read
Abstract Factory Method Design Pattern in Java
The Abstract Factory Method Design Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern allows you to encapsulate a group of individual factories that have a common theme without needing to know the exact classes that will be c
8 min read
Bridge Method Design Pattern in Java
The Bridge Design Pattern is a structural design pattern that decouples an abstraction from its implementation so that the two can vary independently. This pattern is useful when both the abstractions and their implementations should be extensible by subclassing. The Bridge pattern allows us to avoid a permanent binding between an abstraction and i
6 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
System Design Resume Template
Professional SummaryHighly proficient system design engineer with some years of experience in architecting, implementing, and optimizing large-scale, distributed systems. Expertise in creating resilient, scalable, and high-performance solutions. Proven ability to lead complex projects and deliver innovative system architectures. Tips to Write a Sys
5 min read
Design Patterns in Java - Iterator Pattern
A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. Using design patterns you can make your code more f
5 min read
Mediator Design Pattern in Java
The mediator design pattern defines an object that encapsulates how a set of objects interact. The Mediator is a behavioral pattern (like the Observer or the Visitor pattern) because it can change the program's running behavior. We are used to see programs that are made up of a large number of classes. However, as more classes are added to a progra
4 min read