Template Method Design Pattern in Java
A parent class fixes the steps of an algorithm. Child classes fill in only the steps that are different.
Real life example
Making a hot drink: boil water, brew, pour. Only the brewing is different for tea and coffee.
When to use
Several classes follow the same steps but a few steps are different.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
new Tea().prepare(); // Boil water, Steep tea leaves, Pour in cup
new Coffee().prepare(); // Boil water, Drip coffee, Pour in cup
}
}
abstract class Beverage {
final void prepare() { // the template: fixed order
boilWater();
brew();
pour();
}
void boilWater() { System.out.println("Boil water"); }
void pour() { System.out.println("Pour in cup"); }
abstract void brew(); // children must write this step
}
class Tea extends Beverage { void brew() { System.out.println("Steep tea leaves"); } }
class Coffee extends Beverage { void brew() { System.out.println("Drip coffee"); } }Output
Boil water
Steep tea leaves
Pour in cup
Boil water
Drip coffee
Pour in cup