Template Method Design Pattern in Java
1. Introduction
The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
It allows subclasses to redefine certain steps of an algorithm without changing its structure.
2. Real-World Analogy
Think of a Game Development Framework:
- The process of playing a game follows fixed steps: initialize game → start game → play game → end game.
- Different games (Chess, Football, etc.) have different implementations for these steps, but the order remains the same.
3. Structure of Template Method Pattern
- Abstract Class → Defines the template method and some abstract steps.
- Concrete Classes → Implement the abstract steps with specific behaviors.
4. Custom Implementation Example
Let’s build a Game Framework example with Chess and Football.
Step 1 – Abstract Class
public abstract class Game {
// Template method
public final void play() {
initialize();
startPlay();
playGame();
endPlay();
}
protected abstract void initialize();
protected abstract void startPlay();
protected abstract void gameStatus();
protected abstract void endPlay();
}
Step 2 – Concrete Classes
Chess Game
public class Chess extends Game {
@Override
protected void initialize() {
System.out.println("Chess Game Initialized! Setting up board.");
}
@Override
protected void startPlay() {
System.out.println("Chess Game Started! White moves first.");
}
@Override
protected void gameStatus() {
System.out.println("Players are playing chess...");
}
@Override
protected void endPlay() {
System.out.println("Chess Game Finished!");
}
}
Football Game
public class Football extends Game {
@Override
protected void initialize() {
System.out.println("Football Game Initialized! Setting up teams.");
}
@Override
protected void startPlay() {
System.out.println("Football Game Started! Kick-off!");
}
@Override
protected void gameStatus() {
System.out.println("Players are playing football...");
}
@Override
protected void endPlay() {
System.out.println("Football Game Finished!");
}
}
Step 3 – Client Code
public class TemplateMethodPatternDemo {
public static void main(String[] args) {
Game chess = new Chess();
chess.play();
System.out.println();
Game football = new Football();
football.play();
}
}
5. Output
Chess Game Initialized! Setting up board.
Chess Game Started! White moves first.
Players are playing chess...
Chess Game Finished!
Football Game Initialized! Setting up teams.
Football Game Started! Kick-off!
Players are playing football...
Football Game Finished!
6. Advantages
- Provides a clear structure for algorithms.
- Allows subclasses to override only specific parts of the algorithm.
- Promotes code reusability and consistency.
7. Real-World Use Cases
- Game development frameworks.
- Report generation systems (PDF, HTML, Excel).
- Workflow automation (Document approval processes).
UI frameworks (Defining layout structures).
Next Blog- Visitor Design Pattern in Java