Java Template Method Pattern
In this page:
What is the Template Method Pattern?
The Template Method pattern defines the overall skeleton of an algorithm in a base class method, deferring some of its individual steps to subclasses, which override just those steps without changing the algorithm's overall structure.
Example: What is the Template Method Pattern?
public class Main {
static abstract class Recipe {
final void make() { // skeleton
boilWater();
addMainIngredient();
}
void boilWater() { System.out.println("Boiling water"); }
abstract void addMainIngredient();
}
static class Tea extends Recipe {
void addMainIngredient() { System.out.println("Adding tea leaves"); }
}
public static void main(String[] args) {
new Tea().make();
}
}
Login to try C/C++/Java/PHP code in the editor
Defining the Algorithm Skeleton
The template method is typically marked final so subclasses can't alter the overall sequence, only their individual implementations, keeping the algorithm's shape consistent across every subclass.
Example: Defining the Algorithm Skeleton
public class Main {
static abstract class Recipe {
final void make() { step1(); step2(); } // final -- subclasses can't reorder this
void step1() { System.out.println("Step 1"); }
abstract void step2();
}
static class Custom extends Recipe {
void step2() { System.out.println("Custom step 2"); }
}
public static void main(String[] args) {
new Custom().make();
}
}
Login to try C/C++/Java/PHP code in the editor
Overriding Specific Steps
Steps declared abstract in the base class must be implemented by every subclass, letting each subclass customize exactly those parts of the algorithm while reusing the shared structure and any concrete steps unchanged.
Example: Overriding Specific Steps
public class Main {
static abstract class Report {
final void generate() { header(); body(); }
void header() { System.out.println("Header"); }
abstract void body(); // must be implemented by every subclass
}
static class SalesReport extends Report {
void body() { System.out.println("Sales data"); }
}
public static void main(String[] args) {
new SalesReport().generate();
}
}
Login to try C/C++/Java/PHP code in the editor
Hook Methods
A hook method has a default implementation in the base class that a subclass can optionally override to influence the template's behavior, such as skipping an optional step, without being required to override it.
Example: Hook Methods
public class Main {
static abstract class Recipe {
final void make() {
step1();
if (wantsExtra()) extra(); // optional hook
}
void step1() { System.out.println("Step 1"); }
boolean wantsExtra() { return false; } // default, overridable
void extra() { System.out.println("Extra step"); }
}
static class Custom extends Recipe {
boolean wantsExtra() { return true; }
}
public static void main(String[] args) {
new Custom().make();
}
}
Login to try C/C++/Java/PHP code in the editor
Template Method vs Strategy
Template Method uses inheritance, with a subclass overriding specific steps of a fixed algorithm defined in a base class, while Strategy uses composition, swapping in an entirely different algorithm object at runtime instead.
Example: Template Method vs Strategy
public class Main {
static abstract class TemplateExample { // inheritance -- subclass overrides one step
final void run() { System.out.println("Fixed structure, step overridden: " + step()); }
abstract String step();
}
interface StrategyExample { String algorithm(); } // composition -- swap the whole algorithm object
public static void main(String[] args) {
new TemplateExample() { String step() { return "custom"; } }.run();
StrategyExample strategy = () -> "different algorithm";
System.out.println(strategy.algorithm());
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Java Design Patterns Introduction
- Java Singleton Pattern
- Java Factory Pattern
- Java Observer Pattern
- Java Builder Pattern
- Java MVC Architecture
- Java Adapter Pattern
- Java Decorator Pattern
- Java Strategy Pattern
- Java Command Pattern
- Java Facade Pattern
- Java Proxy Pattern
- Java Template Method Pattern
- Java Repository Pattern