Template Method: Defining Algorithm Skeletons
Define the skeleton of an algorithm in a base class and let subclasses fill in the steps.
The Template Method Intent
Template Method defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. Subclasses can override steps without changing the overall structure.
The Abstract Base Class
The base class has the template method (usually final) that orchestrates the steps. Abstract methods represent the varying steps. Concrete methods provide default behavior.
public abstract class DataProcessor {
// Template method — final, defines the algorithm
public final void process() {
readData();
processData();
writeResult();
}
protected abstract void readData();
protected abstract void processData();
protected void writeResult() {
System.out.println("Result written (default)");
}
}All lessons in this course
- Observer Pattern: Event Notification
- Strategy Pattern: Interchangeable Algorithms
- Command Pattern: Encapsulating Actions
- Template Method: Defining Algorithm Skeletons