Overview
The Template Method Design Pattern defines the skeleton of an algorithm in a superclass while allowing subclasses to redefine certain steps without changing the algorithm's structure.
Key Characteristics
- Encapsulates the invariant parts of an algorithm in a superclass.
- Allows subclasses to customize specific steps of the algorithm.
- Promotes code reuse and consistency across implementations.
Implementation
The following is an example of a Template Method implementation in Java:
// Abstract class
abstract class Game {
// Template method
public final void play() {
initialize();
startPlay();
endPlay();
}
protected abstract void initialize();
protected abstract void startPlay();
protected abstract void endPlay();
}
// Concrete class 1
class Football extends Game {
@Override
protected void initialize() {
System.out.println("Football Game Initialized. Start playing.");
}
@Override
protected void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
@Override
protected void endPlay() {
System.out.println("Football Game Finished!");
}
}
// Concrete class 2
class Cricket extends Game {
@Override
protected void initialize() {
System.out.println("Cricket Game Initialized. Start playing.");
}
@Override
protected void startPlay() {
System.out.println("Cricket Game Started. Enjoy the game!");
}
@Override
protected void endPlay() {
System.out.println("Cricket Game Finished!");
}
}
// Demo
public class TemplateMethodDemo {
public static void main(String[] args) {
Game game = new Football();
game.play();
System.out.println();
game = new Cricket();
game.play();
}
}
When to Use
- When you want to enforce a specific sequence of steps in an algorithm.
- When there are common behaviors across subclasses that can be shared in a base class.
Advantages
- Promotes code reuse by putting shared logic in a base class.
- Allows subclasses to customize only the specific parts of an algorithm.
Disadvantages
- Can be challenging to maintain if the template method grows too complex.
- Forces subclasses to follow a predefined structure, limiting flexibility.