Sub topic 16
The Template Method Pattern
Sometimes several classes do a job in the same order, and only one step differs between them. You could copy the same steps into every class, but copied code is hard to keep in sync. If you fix a bug in one copy, you have to remember to fix it in all the others.
The template method pattern solves this problem with an abstract class. A design pattern is a well-known, reusable way to solve a common design problem. In this pattern, the abstract class fixes the order of the steps once. Each subclass fills in only the step that is different.
This chapter combines two things you already know: abstract classes that hold shared code, and polymorphic references to an abstract type.
The Problem: Same Steps, One Different Part
Imagine a program that prints reports. Every report has three parts:
- A header at the top.
- A body with the real content.
- A footer at the bottom.
A sales report and a stock report have the same header and footer. Only the body changes. You want to:
- write the "header, then body, then footer" order once,
- stop subclasses from changing that order by accident,
- force every subclass to supply its own body.
How the Pattern Works
The pattern has two kinds of methods.
- The template method is a method in the abstract class that runs the steps in a fixed order. It is usually marked
final. Afinalmethod cannot be overridden, so no subclass can change the order. - The steps are methods that the template method calls. A step can be one of two kinds:
- An abstract step has no body. Every concrete subclass must implement it.
- A hook is a step that already has a default body. A subclass may override it but does not have to.
A Worked Example
Here is the smallest working version of the pattern.
abstract class DataReport {
public final String generate() {
return header() + "\n" + body() + "\n" + footer();
}
protected String header() {
return "=== Report ===";
}
protected abstract String body();
protected String footer() {
return "=== End ===";
}
}
class SalesReport extends DataReport {
@Override
protected String body() {
return "Total sales: 42";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new SalesReport().generate());
}
}The program prints:
=== Report ===
Total sales: 42
=== End ===Here is what happens, step by step:
maincreates aSalesReportand callsgenerate().SalesReportdoes not definegenerate(), so Java runs the one it inherits fromDataReport.generate()callsheader().SalesReportdid not override it, so the default runs.generate()callsbody(). This is abstract inDataReport, so Java runs the version inSalesReport.generate()callsfooter(), and the default runs again.
The parent class controls the order of the steps. The subclass supplies one piece. People sometimes call this the "Hollywood principle": don't call us, we'll call you. The subclass never calls generate() itself. It waits for the parent's code to call its body() method.
Adding a Second Report and Overriding a Hook
Now add a stock report that also changes its header. The program below has two subclasses and uses them through one abstract type.
abstract class DataReport {
public final String generate() {
return header() + "\n" + body() + "\n" + footer();
}
protected String header() {
return "=== Report ===";
}
protected abstract String body();
protected String footer() {
return "=== End ===";
}
}
class SalesReport extends DataReport {
@Override
protected String body() {
return "Total sales: 42";
}
}
class StockReport extends DataReport {
@Override
protected String header() {
return "=== Stock Report ===";
}
@Override
protected String body() {
return "Items in stock: 7";
}
// public String generate() { return "oops"; }
// compile error: overridden method is final
}
public class Main {
public static void main(String[] args) {
DataReport[] reports = { new SalesReport(), new StockReport() };
for (DataReport r : reports) {
System.out.println(r.generate());
System.out.println();
}
}
}Output:
=== Report ===
Total sales: 42
=== End ===
=== Stock Report ===
Items in stock: 7
=== End ===The loop only knows about DataReport. Each object still runs its own body() and, for StockReport, its own header(). That is polymorphism working inside the template method.
Why the Modifiers Matter
Each keyword in the example has a job.
| Modifier | Where | Why it is there |
|---|---|---|
| `abstract` on the class | `DataReport` | Nobody can create a plain report that has no body. |
| `final` | `generate()` | Subclasses cannot change the order of the steps. |
| `abstract` | `body()` | Every concrete subclass must supply the body. The compiler checks this. |
| `protected` | the steps | Subclasses can override them, but outside code is meant to call `generate()` instead. |
| `public` | `generate()` | Outside code uses this one method as the entry point. |
Common Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Forgetting `final` on the template method | A subclass can override it and skip or reorder steps. | Mark the template method `final`. |
| Making every step abstract | Every subclass must write the header and footer again, even when they are identical. | Give shared steps a default body (a hook). |
| Making steps `public` | Callers may run `body()` alone and skip the header. | Make the steps `protected`. |
| Calling the template method from the constructor | The subclass's fields are not set yet, so steps may see `null` or `0`. | Call the template method after the object is fully built. |
When to Use the Pattern
The template method pattern fits well when:
- several classes follow the same sequence of steps,
- only a few steps differ between them,
- you want the parent class to guarantee the order.
It fits less well when a class needs to plug in behavior from several unrelated sources. A class can extend only one abstract class. The final chapter compares this choice with interfaces in more detail.
Exercise
In the DataReport example, what would go wrong if generate() were not marked final?
Show answer
A subclass could override generate() and change or skip steps. For example, it could return only the body with no header or footer. The parent class would no longer guarantee the "header, body, footer" order, and that guarantee is the whole point of the pattern.
Exercise
Write a subclass ErrorReport of DataReport whose body is "Errors: 0" and whose footer is "=== No problems ===". What does new ErrorReport().generate() return?
Show answer
class ErrorReport extends DataReport { @Override protected String body() { return "Errors: 0"; } @Override protected String footer() { return "=== No problems ==="; } }. The call returns "=== Report ===\nErrors: 0\n=== No problems ===". The header uses the default hook, the body comes from the required abstract step, and the footer comes from the overridden hook.
Exercise
What is the difference between an abstract step and a hook in the template method pattern?
Show answer
An abstract step has no body, so every concrete subclass must implement it, and the compiler enforces this. A hook already has a default body in the abstract class. A subclass may override it to change that step, but it does not have to.