Introduction
Imagine you are building an online payment system.
Different payment methods exist:
Credit Card
UPI
PayPal
Although the payment methods differ, the overall payment process remains largely the same:
Validate Payment Details
Process Payment
Generate Receipt
Send Confirmation
A beginner might write separate classes like:
Notice something?
The workflow is almost identical.
Only a few steps differ.
This leads to duplicated code and maintenance problems.
The Template Method Pattern solves this problem.
What is the Template Method Pattern?
The Template Method 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.
In simple words:
Define the overall process once and allow subclasses to customize certain parts of it.
The sequence of steps remains fixed, but some individual steps can vary.
Real World Analogy
Imagine making tea and coffee.
Tea Preparation:
Boil Water
Add Tea Leaves
Pour Into Cup
Serve
Coffee Preparation:
Boil Water
Add Coffee Powder
Pour Into Cup
Serve
The overall process is the same.
Only one step changes.
Instead of rewriting the entire process for every beverage, we can define the common workflow once and allow subclasses to customize specific steps.
Why Do We Need the Template Method Pattern?
Suppose we are building a report generation system.
Different reports exist:
PDF Report
Excel Report
CSV Report
Without Template Method:
Notice that:
fetchData() is common
processData() is common
sendEmail() is common
Only export logic changes.
This creates code duplication.
Problems Without Template Method
1. Code Duplication
Common steps get repeated across multiple classes.
2. Difficult Maintenance
Changing the workflow requires updating multiple classes.
3. Inconsistent Implementation
Different developers may accidentally change the sequence.
Example:
Class A:
A → B → C → D
Class B:
A → C → B → D
The workflow becomes inconsistent.
4. Violates DRY Principle
DRY stands for:
Don't Repeat Yourself
Repeated workflow logic violates this principle.
Solution: Template Method Pattern
The Template Method Pattern moves the common workflow into a base class.
The base class defines:
Step 1
Step 2
Step 3
Step 4
Subclasses customize only the steps that differ.
Key Components of Template Method Pattern
The Template Method Pattern typically contains:
1. Abstract Class
Contains the template method.
2. Template Method
Defines the overall algorithm flow.
3. Abstract Steps
Steps that subclasses must implement.
4. Concrete Steps
Common steps implemented in the base class.
5. Concrete Subclasses
Provide specific implementations for variable steps.
Structure of Template Method Pattern
Abstract Class
│
▼
Template Method
Step A
Step B
Step C
▲
│
Subclasses Override
Specific Steps
Example: Beverage Preparation System
Let's build a beverage preparation system.
Step 1: Create Abstract Class
Understanding the Template Method
The method:
prepareBeverage()
is the Template Method.
It defines the entire workflow.
The sequence cannot be changed by subclasses.
Step 2: Create Tea Class
Step 3: Create Coffee Class
Step 4: Client Code
Output
Boiling Water
Adding Tea Leaves
Pouring Into Cup
Serving Beverage
Boiling Water
Adding Coffee Powder
Pouring Into Cup
Serving Beverage
How the Template Method Works
Let's understand the flow.
Step 1
Client calls:
Step 2
The base class executes the algorithm.
Step 3
When a customizable step appears:
The subclass implementation runs.
Step 4
Control returns to the base class.
The workflow continues.
Hooks in the Template Method Pattern
A hook is an optional method that subclasses may override.
Example:
Template Method:
Subclasses can choose whether to override the hook.
Hooks provide additional flexibility.
Example of Hook
Now coffee will be prepared without sugar.
Template Method vs Strategy Pattern
This is a very common interview question.
Both patterns deal with algorithms.
However, their approach is different.
| Template Method | Strategy Pattern |
|---|---|
| Uses inheritance | Uses composition |
| Algorithm structure fixed | An algorithm can change completely |
| Subclasses customize steps | Strategies replace behavior |
| Compile-time flexibility | Runtime flexibility |
| Base class controls workflow | Client selects strategy |
Example Difference
Template Method:
Make Beverage
Boil Water
Add Ingredient
Serve
Workflow remains fixed.
Strategy:
Payment Strategy
Card
UPI
PayPal
Entire algorithm changes.
Advantages of Template Method Pattern
1. Eliminates Code Duplication
Common workflow exists only once.
2. Promotes Code Reuse
Shared logic stays in the base class.
3. Enforces Consistent Workflow
Subclasses cannot accidentally change the algorithm order.
4. Supports the Open-Closed Principle
New subclasses can be added without modifying existing code.
5. Easier Maintenance
Changes in common logic occur in one place.
Disadvantages of Template Method Pattern
1. Relies on Inheritance
Inheritance can create tight coupling.
2. Limited Flexibility
The workflow sequence cannot easily change.
3. Large Base Classes
Too many steps can make the base class difficult to maintain.
Real World Applications
The Template Method Pattern is commonly used in:
Framework design
Report generation systems
Payment processing systems
Data import/export pipelines
Build systems
Testing frameworks
Authentication workflows
File processing systems
Game engines
Many frameworks internally use the Template Method to define lifecycle methods.
Common Beginner Mistakes
1. Confusing Template Method with Strategy
Remember:
Template Method = Inheritance
Strategy = Composition
2. Putting Everything in the Base Class
Only the common workflow should remain in the parent class.
3. Making Too Many Abstract Methods
Too many customizable steps make the design complicated.
4. Allowing Workflow Modification
The template method should usually remain fixed.
Subclasses should customize steps, not the overall flow.
Simple Visualization
Without Template Method:
Tea Class
A → B → C → D
Coffee Class
A → E → C → D
Lots of duplicated logic.
With Template Method:
Base Class
A → ? → C → D
▲
│
Tea Coffee
B E
The workflow stays in one place while subclasses provide custom behavior.
Summary
The Template Method Design Pattern defines the skeleton of an algorithm in a base class while allowing subclasses to customize individual steps.
Instead of duplicating the entire workflow across multiple classes, common logic is centralized and variable behavior is delegated to subclasses. This promotes code reuse, consistency, and maintainability while ensuring that the overall process remains unchanged.
Whenever multiple classes follow the same workflow but differ in a few specific steps, the Template Method Pattern provides a clean and effective solution.