Template Method
Define skeleton of algorithm in base class
Overview
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
Key Concepts
Abstract Class defines the template method (often final) containing the algorithm skeleton
Abstract/Hooks methods are overridden by concrete classes
Code Example
java
1public abstract class BeverageMaker {
2 // Template method
3 public final void makeBeverage() {
4 boilWater();
5 brew();
6 pourInCup();
7 if (customerWantsCondiments()) {
8 addCondiments();
9 }
10 }
11
12 void boilWater() { System.out.println("Boiling water"); }
13 void pourInCup() { System.out.println("Pouring into cup"); }
14
15 // Hooks/Abstract methods
16 abstract void brew();
17 abstract void addCondiments();
18
19 // Hook with default implementation
20 boolean customerWantsCondiments() { return true; }
21}
22
23public class TeaMaker extends BeverageMaker {
24 @Override void brew() { System.out.println("Steeping tea"); }
25 @Override void addCondiments() { System.out.println("Adding lemon"); }
26}