Template Method helps when one process skeleton is stable but a few steps should vary in controlled ways.
Define the skeleton of an algorithm in one operation and let subclasses redefine certain steps without changing the algorithm’s overall structure.
What the pattern is trying to do
Define the skeleton of an algorithm in one operation and let subclasses redefine certain steps without changing the algorithm’s overall structure.
What force creates the need
Several processes follow the same broad sequence, but a few steps differ and repeated duplication is growing.
How the pattern responds
Keep the stable algorithm in a base class and expose specific hook methods for subclasses to vary.
How the moving parts fit together
A base class defines the template flow and delegates specific steps to overridable methods implemented by subclasses.
Java example in the Order Management domain
package org.javaomnibus.ecommerce.gof.behavioral;
public abstract class ReceiptRenderer {
public final String render(Order order) {
return header(order) + body(order) + footer(order);
}
protected String header(Order order) {
return "Receipt\n";
}
protected abstract String body(Order order);
protected String footer(Order order) {
return "\nThank you";
}
}
Step by step
- The render method defines the stable process skeleton.
- Subclasses vary only the intended steps.
- This preserves the overall algorithm while allowing controlled customization.
- Template Method is strongest when the sequence is genuinely stable.
Where this pattern helps
- When one algorithm structure is fixed but a few steps vary
- When inheritance-based variation is acceptable and explicit
When a simpler design is better
- When composition would be more flexible than inheritance
- When the process skeleton itself is unstable
What this pattern costs
- Inheritance makes variation less flexible than composition-based approaches
- Overuse can create brittle base classes
How this fits today
Template Method still appears in framework base classes, rendering flows, import/export pipelines, and testing scaffolds, though many teams now prefer composition where practical.
Where teams get it wrong
Using Template Method where strategies or composed collaborators would be clearer can trap the design in rigid inheritance hierarchies.