Template Method Design Pattern in Java with Examples | Beginner to Advanced Guide

Reading Time: 11–14 minutes

The Template Method Design Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class and allows subclasses to override specific steps without changing the overall structure.

This pattern is useful when multiple classes follow the same process but differ in certain steps. It promotes code reuse, consistency, and follows the Open Closed Principle.

This tutorial explains the Template Method pattern from beginner to advanced level with simple examples, step-by-step implementation, and real-world understanding.

What is Template Method Design Pattern

The Template Method pattern defines the overall structure of an algorithm in a base class method and allows subclasses to implement or override certain steps.

Simple definition:

Template Method defines “how a process works” while subclasses define “how specific steps are performed”.

Why Do We Need Template Method Pattern

Many systems follow a fixed process flow but differ in certain steps.

Problem Without Template Method

Suppose we build a system for processing different types of online orders.


package com.codekatha;

class OnlineOrder {

    public void processOrder() {
        validateOrder();
        processPayment();
        deliverOrder();
    }

    public void validateOrder() {
        System.out.println("Validating online order");
    }

    public void processPayment() {
        System.out.println("Processing online payment");
    }

    public void deliverOrder() {
        System.out.println("Delivering online order");
    }
}

If we add OfflineOrder or InternationalOrder, we may duplicate the entire process with slight modifications.

Problems in This Approach

Code duplication
Hard to maintain
Process structure may break
Difficult to enforce consistent workflow

Solution – Template Method Pattern

We define the complete process in a base abstract class. Some methods are implemented, while others are left abstract for subclasses.

The template method ensures the execution order remains fixed.

Key Idea Behind Template Method

Define algorithm structure in base class
Allow subclasses to customize certain steps
Prevent modification of overall workflow

Structure of Template Method Pattern

Abstract Class → Defines template method
Concrete Classes → Implement specific steps
Template Method → Final method defining workflow

Step-by-Step Template Method Implementation

Step 1 – Create Abstract Base Class


package com.codekatha;

abstract class OrderProcessor {

    // Template method
    public final void processOrder() {
        validateOrder();
        processPayment();
        deliverOrder();
    }

    protected abstract void validateOrder();

    protected abstract void processPayment();

    protected void deliverOrder() {
        System.out.println("Order delivered successfully");
    }
}

The method processOrder() is final to prevent subclasses from changing the algorithm structure.

Step 2 – Create Concrete Classes


package com.codekatha;

class OnlineOrder extends OrderProcessor {

    protected void validateOrder() {
        System.out.println("Validating online order");
    }

    protected void processPayment() {
        System.out.println("Processing online payment");
    }
}

class StorePickupOrder extends OrderProcessor {

    protected void validateOrder() {
        System.out.println("Validating store pickup order");
    }

    protected void processPayment() {
        System.out.println("Processing payment at store");
    }
}

Step 3 – Client Code


package com.codekatha;

class TemplateDemo {

    public static void main(String[] args) {

        OrderProcessor order = new OnlineOrder();
        order.processOrder();

        System.out.println("-----");

        order = new StorePickupOrder();
        order.processOrder();
    }
}

What We Achieved Using Template Method

Fixed process structure
Reduced code duplication
Controlled workflow
Customizable steps
Better maintainability

Understanding Template Method with Simple Analogy

Think of preparing tea and coffee.

Boil water
Add main ingredient (tea leaves or coffee)
Pour into cup
Serve

The steps are similar, but one step differs. The overall process remains fixed.

Hook Methods in Template Pattern

Hook methods are optional methods that subclasses may override.


protected void applyDiscount() {
    // optional step
}

Hooks provide additional flexibility.

Template Method vs Strategy Pattern

Template Method uses inheritance.
Strategy uses composition.

Key Difference

Template Method → Algorithm fixed in base class.
Strategy → Algorithm selected at runtime.

Advantages of Template Method Pattern

Promotes code reuse
Ensures consistent workflow
Follows Open Closed Principle
Reduces duplication
Easy to extend

Disadvantages of Template Method Pattern

Uses inheritance heavily
May increase number of subclasses
Less flexible compared to Strategy

When Should You Use Template Method Pattern

When multiple classes share common workflow
When algorithm structure must remain fixed
When some steps vary across implementations
When enforcing process consistency

Real-World Usage of Template Method

Spring Framework’s JdbcTemplate
Servlet lifecycle methods
JUnit test framework
Data processing pipelines

Common Interview Questions on Template Method

What problem does Template Method solve?
Difference between Strategy and Template Method?
Why make template method final?
Real-world example?

Simple Summary

Template Method defines algorithm structure.
Subclasses customize certain steps.
Workflow remains fixed.
Promotes reuse and maintainability.

Conclusion

The Template Method Design Pattern helps enforce a consistent process while allowing flexibility in specific steps. It is ideal when multiple implementations share a common workflow.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Spring AI with Ollama

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts