you fix the overall flow but let sub-classes customize some parts.
The Template method pattern defines the skeleton(Template) of an algorithm in a base class.
It Allows sub-classes to override certain steps of the algorithms without changing its overall structure.
Warning
You might violate the Liskov Substitution Principle by suppressing a default step implementation via a subclass.
Template methods tend to be harder to maintain the more steps they have.
A typical architectural plan can be slightly altered to better fit the client’s needs.
The template method approach can be used in mass housing construction. The architectural plan for building a standard house may contain several extension points that would let a potential owner adjust some details of the resulting house.
Each building step, such as laying the foundation, framing, building walls, installing plumbing and wiring for water and electricity, etc.,can be slightly changed to make the resulting house a little bit different from others.
Structure

When to Use
- You have an algorithm where some steps vary but the overall structure is fixed.
- You want to avoid duplicating common code.
- You want to follow the Hollywood Principle → “Don’t call us, we’ll call you” → the base class controls the flow and calls subclass hooks.
Real world example
- Making coffee vs. tea (brewing differences)
- Game AI skeleton with customizable decision logic
- Document renderers (HTML, PDF, Word) with shared layout steps
- Sorting frameworks where you plug in your comparison function
Example
// Abstract class defining the template method
abstract class DataProcessor {
// Template method (final to prevent overriding)
public final void process() {
readData();
processData();
saveResults();
}
// Steps to be implemented by subclasses
abstract void readData();
abstract void processData();
// Common step (can be overridden if needed)
void saveResults() {
System.out.println("Saving results to database.");
}
}
// Concrete subclass for CSV
class CSVDataProcessor extends DataProcessor {
void readData() {
System.out.println("Reading CSV data.");
}
void processData() {
System.out.println("Processing CSV data.");
}
}
// Concrete subclass for XML
class XMLDataProcessor extends DataProcessor {
void readData() {
System.out.println("Reading XML data.");
}
void processData() {
System.out.println("Processing XML data.");
}
}
// Main class to run the example
public class TemplateMethodDemo {
public static void main(String[] args) {
DataProcessor csvProcessor = new CSVDataProcessor();
System.out.println("=== CSV Processing ===");
csvProcessor.process();
System.out.println();
DataProcessor xmlProcessor = new XMLDataProcessor();
System.out.println("=== XML Processing ===");
xmlProcessor.process();
}
}