Template Method Design Pattern in Java
Learn Template Method Design Pattern in Java with workflow standardization, Spring JdbcTemplate, batch processing, enterprise frameworks, UML diagrams, Java implementation, and real-world examples.
What You Will Learn
- What is Template Method Pattern?
- Why Template Method Pattern is Needed
- Workflow Standardization
- Java Implementation
- Spring JdbcTemplate Example
- Batch Processing Example
- Enterprise Use Cases
- Benefits and Limitations
- Interview Questions
Introduction
Many enterprise applications follow the same workflow but differ in certain steps.
Examples:
Process Payment
Validate Request
Execute Payment
Send Notification
Different payment methods:
Credit Card
PayPal
UPI
The workflow is same.
Only implementation changes.
Without Template Method:
if(type.equals("CARD")) {
validate();
processCard();
notifyUser();
}
else if(type.equals("UPI")) {
validate();
processUpi();
notifyUser();
}
Code duplication increases.
Template Method solves this problem.
What is Template Method Pattern?
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.
Simple View:
Common Workflow
↓
Fixed Steps
↓
Custom Implementation
Purpose of Template Method
Primary Goal:
Reuse Common Workflow
While Allowing
Custom Behavior
Real World Analogy
Making Coffee and Tea.
Steps:
Boil Water
Add Main Ingredient
Pour Into Cup
Serve
Coffee:
Add Coffee Powder
Tea:
Add Tea Leaves
Workflow is same.
Implementation differs.
Problem Without Template Method
flowchart LR
A[Coffee Logic]
B[Tea Logic]
C[Milk Logic]
A --> B
B --> C
Repeated workflow logic.
Hard maintenance.
Solution With Template Method
flowchart LR
A[Abstract Workflow]
B[Coffee]
C[Tea]
D[Milk]
A --> B
A --> C
A --> D
Shared workflow.
Custom implementation.
Template Method Architecture
flowchart LR
A[Abstract Class]
B[Template Method]
C[Concrete Class A]
D[Concrete Class B]
A --> B
A --> C
A --> D
Key Components
Abstract Class
Defines workflow.
Template Method
Defines fixed sequence of operations.
Concrete Class
Implements variable steps.
UML Diagram
classDiagram
class PaymentProcessor {
+processPayment()
+validate()
+executePayment()
+sendNotification()
}
class CreditCardProcessor
class UpiProcessor
PaymentProcessor <|-- CreditCardProcessor
PaymentProcessor <|-- UpiProcessor
Payment Processing Example
Workflow:
Validate
Process Payment
Generate Receipt
Send Notification
Every payment type follows this flow.
Step 1: Abstract Class
public abstract class PaymentProcessor {
public final void processPayment() {
validate();
executePayment();
generateReceipt();
sendNotification();
}
protected abstract void validate();
protected abstract void executePayment();
protected void generateReceipt() {
System.out.println(
"Receipt Generated");
}
protected void sendNotification() {
System.out.println(
"Notification Sent");
}
}
Step 2: Credit Card Processor
public class CreditCardProcessor
extends PaymentProcessor {
@Override
protected void validate() {
System.out.println(
"Validating Card");
}
@Override
protected void executePayment() {
System.out.println(
"Processing Card Payment");
}
}
Step 3: UPI Processor
public class UpiProcessor
extends PaymentProcessor {
@Override
protected void validate() {
System.out.println(
"Validating UPI");
}
@Override
protected void executePayment() {
System.out.println(
"Processing UPI Payment");
}
}
Step 4: Client
public class TemplateDemo {
public static void main(
String[] args) {
PaymentProcessor processor =
new CreditCardProcessor();
processor.processPayment();
}
}
Output
Validating Card
Processing Card Payment
Receipt Generated
Notification Sent
Execution Flow
flowchart LR
A[Validate]
B[Process Payment]
C[Generate Receipt]
D[Send Notification]
A --> B
B --> C
C --> D
Hook Methods
Template Method supports optional steps.
Example:
protected boolean shouldNotify() {
return true;
}
Template:
if(shouldNotify()) {
sendNotification();
}
Hook Flow
flowchart LR
A[Process Payment]
B[Check Hook]
C[Send Notification]
A --> B
B --> C
Banking Example
Loan Processing Workflow:
Validate Application
Credit Check
Approval Decision
Disbursement
Different loan types:
Home Loan
Car Loan
Personal Loan
Use same workflow.
Banking Workflow
flowchart LR
A[Validation]
B[Credit Check]
C[Approval]
D[Disbursement]
A --> B
B --> C
C --> D
Insurance Example
Claim Processing:
Validate Claim
Verify Documents
Fraud Check
Approve Claim
Insurance Workflow
flowchart LR
A[Validate Claim]
B[Document Check]
C[Fraud Check]
D[Approval]
A --> B
B --> C
C --> D
Spring JdbcTemplate Example
One of the best real-world examples.
Without JdbcTemplate:
Open Connection
Create Statement
Execute Query
Process Result
Close Connection
Repeated everywhere.
JdbcTemplate Handles
jdbcTemplate.query(
sql,
rowMapper);
Framework manages:
Connection
Statement
Exception Handling
Resource Cleanup
Developer provides:
RowMapper
Only variable part.
JdbcTemplate Flow
flowchart LR
A[Open Connection]
B[Execute Query]
C[Row Mapper]
D[Close Connection]
A --> B
B --> C
C --> D
Spring Batch Example
Batch Workflow:
Read
Process
Write
Same structure.
Different implementations.
Spring Batch Flow
flowchart LR
A[Reader]
B[Processor]
C[Writer]
A --> B
B --> C
Enterprise Examples
Banking
Loan Processing
Account Opening
KYC Verification
Insurance
Claim Processing
Policy Approval
Retail
Order Processing
Shipment Processing
Healthcare
Patient Registration
Treatment Workflow
Framework Examples
Common Template Method implementations:
Spring JdbcTemplate
RestTemplate
RedisTemplate
KafkaTemplate
Hibernate Template
Benefits
✅ Eliminates Code Duplication
✅ Reuses Common Workflow
✅ Supports Open Closed Principle
✅ Easier Maintenance
✅ Consistent Processing Logic
✅ Framework Friendly
Limitations
❌ Uses Inheritance
❌ Deep Hierarchies Can Become Complex
❌ Less Flexible Than Composition
When To Use
Use Template Method when:
- Workflow is fixed
- Only a few steps vary
- Code duplication exists
- Multiple implementations share same process
When Not To Use
Avoid when:
- Entire algorithm changes
- Runtime switching is required
Use Strategy Pattern instead.
Template Method vs Strategy
| Feature | Template Method | Strategy |
|---|---|---|
| Uses | Inheritance | Composition |
| Runtime Change | No | Yes |
| Flexibility | Medium | High |
| Workflow | Fixed | Dynamic |
Template Method vs Factory Method
| Feature | Template Method | Factory Method |
|---|---|---|
| Focus | Algorithm Workflow | Object Creation |
| Type | Behavioral | Creational |
| Purpose | Process Reuse | Object Instantiation |
Real Enterprise Architecture
flowchart LR
A[Application]
B[Template Workflow]
C[Custom Step]
D[Business Logic]
A --> B
B --> C
C --> D
Interview Questions
What is Template Method Pattern?
A behavioral pattern that defines the skeleton of an algorithm and allows subclasses to implement specific steps.
Main Components?
Abstract Class
Template Method
Concrete Class
Why is Template Method Useful?
It removes duplicate workflow code.
Real Spring Example?
JdbcTemplate
RestTemplate
RedisTemplate
KafkaTemplate
Difference Between Strategy and Template Method?
Strategy uses composition and supports runtime switching.
Template Method uses inheritance and defines fixed workflows.
Key Takeaways
- Template Method is a Behavioral Design Pattern.
- Defines workflow skeleton in a base class.
- Allows subclasses to customize certain steps.
- Eliminates duplicate code.
- Widely used in Spring Framework templates.
- Great for workflow-driven enterprise systems.
- Common in Banking, Insurance, Retail, and Batch Processing systems.