Skip to lesson

Template Method: fixed steps, custom details

ShopLite exports order reports as CSV for accounts and as plain text for email. Each was written on its own, and the text version quietly lost its total line. How can both always follow the same steps?

An abstract class with a final template method

Template method is a public final method in an abstract base class that runs the steps of a job in a fixed order. It calls abstract step methods for the parts that differ, and each subclass fills those in.

Both reports do the same steps: a header, one line per order, then a total. Below is that shared recipe in one abstract class.

Java
abstract class ReportExporter {    public final String export(List<Order> orders) {       // the template: fixed steps        StringBuilder out = new StringBuilder(header() + "\n");        int total = 0;        for (Order o : orders) {            out.append(row(o)).append("\n");            total += o.amount();        }        return out.append(totalLine(total)).toString();    }
    protected abstract String header();                     // steps a subclass fills in    protected abstract String row(Order o);    protected abstract String totalLine(int total);}

Example 1 · Before: two exporters copy the same steps

CopiedStepsDemo.javaJava
import java.util.List;
record Order(String id, String customer, String city, int amount) {}
class CsvExport {    String export(List<Order> orders) {        StringBuilder out = new StringBuilder("id,customer,amount\n");        int total = 0;        for (Order o : orders) {            out.append(o.id()).append(",").append(o.customer()).append(",").append(o.amount()).append("\n");            total += o.amount();        }        out.append("TOTAL,,").append(total).append("\n");        return out.toString();    }}
class TextExport {    String export(List<Order> orders) {        StringBuilder out = new StringBuilder("Orders\n");        for (Order o : orders) {            out.append(o.id()).append("  ").append(o.customer()).append("  Rs ").append(o.amount()).append("\n");        }        return out.toString();                    // the total line was forgotten here    }}
public class CopiedStepsDemo {    public static void main(String[] args) {        List<Order> orders = List.of(new Order("A101", "Riya", "Pune", 1799), new Order("A103", "Meena", "Kochi", 2999));        System.out.print(new CsvExport().export(orders));        System.out.print(new TextExport().export(orders));    }}
Output
id,customer,amount
A101,Riya,1799
A103,Meena,2999
TOTAL,,4798
Orders
A101  Riya  Rs 1799
A103  Meena  Rs 2999

What this code does

  • Both classes repeat the same plan: header, loop, total. Nothing forces them to keep the same plan, and the text version quietly lost its total.
  • The template method in the snippet above fixes the plan once, so a subclass can change the look of a line but not skip one.

Written twice, the steps drift apart, and sooner or later one copy forgets the total. The template method keeps them in one place. Making it final means no subclass can change the order of the steps or skip one.

Abstract steps and optional hook methods

Hook is a step in a template method that has a default body, often empty or returning true. A subclass may override it to adjust the flow, but does not have to.

An abstract step has no body, so every subclass must write it. A hook has a default body that a subclass may override. Below, send is the template.

Example 2 · Abstract steps and hooks in an order message

HookDemo.javaJava
record Order(String id, String customer, String city, int amount) {}
abstract class OrderMessage {    public final void send(Order o) {        if (!shouldSend(o)) {            System.out.println("(skipped " + o.id() + ")");            return;        }        System.out.println(subject(o));        System.out.println("  " + body(o));        System.out.println("  " + signature());    }
    protected abstract String subject(Order o);    protected abstract String body(Order o);
    protected boolean shouldSend(Order o) { return true; }     // hooks with defaults    protected String signature() { return "- Team ShopLite"; }}
class EmailMessage extends OrderMessage {    protected String subject(Order o) { return "EMAIL: Order " + o.id() + " confirmed"; }    protected String body(Order o) { return "Hi " + o.customer() + ", we received Rs " + o.amount() + "."; }}
class SmsMessage extends OrderMessage {    protected String subject(Order o) { return "SMS: " + o.id(); }    protected String body(Order o) { return "Paid Rs " + o.amount(); }
    @Override    protected boolean shouldSend(Order o) { return o.amount() >= 1000; }   // SMS only for big orders
    @Override    protected String signature() { return "-SL"; }                         // SMS must be short}
public class HookDemo {    public static void main(String[] args) {        Order big = new Order("A101", "Riya", "Pune", 1799);        Order small = new Order("A102", "Kabir", "Indore", 391);        OrderMessage email = new EmailMessage();        OrderMessage sms = new SmsMessage();        email.send(big);        sms.send(big);        sms.send(small);    }}
Output
EMAIL: Order A101 confirmed
  Hi Riya, we received Rs 1799.
  - Team ShopLite
SMS: A101
  Paid Rs 1799
  -SL
(skipped A102)

What this code does

  • subject and body are abstract, so both subclasses must write them. EmailMessage keeps both hooks' defaults.
  • SmsMessage overrides the hooks: shouldSend skips orders under Rs 1,000 and signature is shorter. The order of the steps still comes from send.

Hooks let a subclass adjust the flow without owning it: includeTotal() can switch the total line off, and beforeRows() can add a title. Keep hooks few and well named; each one is a promise the base class must keep.

To tell them apart: the template is public final, an abstract step is protected abstract, and a hook is protected with a default body.

Predict the output

Predict the template

Read the code, then pick what it prints.

The subclass writes the abstract step and keeps the hook.

abstract class Msg {
public final void send() {
System.out.print("Hello ");
System.out.print(name());
System.out.println(suffix());
}
protected abstract String name();
protected String suffix() { return "!"; }
}
public class Demo {
public static void main(String[] args) {
new Msg() {
protected String name() { return "Riya"; }
}.send();
}
}

Example: report export as CSV and as plain text

CsvExporter writes comma-separated values for spreadsheets, and TextExporter lines up columns for email. Both share one export template.

Example 3 · CsvExporter and TextExporter on one template

ExportDemo.javaJava
import java.util.List;
record Order(String id, String customer, String city, int amount) {}
abstract class ReportExporter {    public final String export(List<Order> orders) {        StringBuilder out = new StringBuilder(header() + "\n");        int total = 0;        for (Order o : orders) {            out.append(row(o)).append("\n");            total += o.amount();        }        if (includeTotal()) {            out.append(totalLine(total)).append("\n");        }        return out.toString();    }
    protected abstract String header();    protected abstract String row(Order o);    protected abstract String totalLine(int total);
    protected boolean includeTotal() {                       // hook        return true;    }}
class CsvExporter extends ReportExporter {    protected String header() { return "id,customer,city,amount"; }
    protected String row(Order o) {        return String.join(",", o.id(), quote(o.customer()), o.city(), String.valueOf(o.amount()));    }
    protected String totalLine(int total) { return "TOTAL,,," + total; }
    private static String quote(String field) {              // a comma inside a field needs quotes        return field.contains(",") ? "\"" + field + "\"" : field;    }}
class TextExporter extends ReportExporter {    private static final String COLS = "%-5s %-14s %-7s %9s";
    protected String header() { return String.format(COLS, "ID", "Customer", "City", "Amount"); }    protected String row(Order o) { return String.format(COLS, o.id(), o.customer(), o.city(), "Rs " + o.amount()); }    protected String totalLine(int total) { return String.format("%-28s %9s", "Total", "Rs " + total); }}
public class ExportDemo {    public static void main(String[] args) {        List<Order> orders = List.of(                new Order("A101", "Riya", "Pune", 1799),                new Order("A102", "Sharma, Kabir", "Indore", 391),                new Order("A103", "Meena", "Kochi", 2999));        System.out.print(new CsvExporter().export(orders));        System.out.println();        System.out.print(new TextExporter().export(orders));    }}
Output
id,customer,city,amount
A101,Riya,Pune,1799
A102,"Sharma, Kabir",Indore,391
A103,Meena,Kochi,2999
TOTAL,,,5189

ID    Customer       City       Amount
A101  Riya           Pune      Rs 1799
A102  Sharma, Kabir  Indore     Rs 391
A103  Meena          Kochi     Rs 2999
Total                          Rs 5189

What this code does

  • The loop and the total are written once, in export. Each subclass only decides what one header, one row and one total line look like.
  • Sharma, Kabir is quoted in the CSV so a spreadsheet keeps it in one column. The text version pads each column with %-14s and right-aligns amounts with %9s.

A CSV field that contains a comma, such as Sharma, Kabir, must be wrapped in double quotes, or the spreadsheet splits it into two columns. TextExporter lines up columns with String.format.

Both classes are short because the loop, the total and the order of lines live in the base class. A third format, such as Markdown for a chat tool, is one more small subclass.

Order of execution

Build the exporters

Put the steps in the order you would do them.

Hollywood principle: the base class calls you

Hollywood principle is the rule "don't call us, we'll call you". The base class controls the flow and calls the subclass's steps when it needs them; the subclass only answers.

AbstractList asks you for just two methods, get and size. Below, a list of recent orders writes only those two.

Example 4 · AbstractList: write get and size, get the rest free

AbstractListDemo.javaJava
import java.util.AbstractList;import java.util.List;
class LastOrders extends AbstractList<String> {    private final String[] ids;
    LastOrders(String... ids) {        this.ids = ids;    }
    @Override    public String get(int index) {                    // called by AbstractList, not by us        System.out.println("    get(" + index + ")");        return ids[ids.length - 1 - index];           // newest first    }
    @Override    public int size() {        return ids.length;    }}
public class AbstractListDemo {    public static void main(String[] args) {        List<String> recent = new LastOrders("A101", "A102", "A103");        System.out.println("contains A101?");        System.out.println("  " + recent.contains("A101"));        System.out.println("indexOf A102:");        System.out.println("  " + recent.indexOf("A102"));        System.out.println("as text: " + String.join(", ", recent));    }}
Output
contains A101?
    get(0)
    get(1)
    get(2)
  true
indexOf A102:
    get(0)
    get(1)
  1
    get(0)
    get(1)
    get(2)
as text: A103, A102, A101

What this code does

  • LastOrders writes only get and size. contains, indexOf and the iterator used by String.join are template methods in AbstractList that call those two methods; the printed get(...) lines show the base class calling us.
  • This is the Hollywood principle in the JDK: we never call get ourselves, yet it runs whenever the base class needs an element.

AbstractList then calls your two methods from its own contains, indexOf, toString and iteration. You never call get yourself, yet it runs whenever the base class needs an element.

Frameworks such as Spring work the same way with callbacks: your code supplies a step and the framework decides when it runs.

Template Method vs Strategy: inheritance vs composition

Both patterns let one part of an algorithm vary. Below, the same export is written with Strategy: the format is passed in, not inherited.

Example 5 · The same export with Strategy instead of inheritance

StrategyExportDemo.javaJava
import java.util.List;
record Order(String id, String customer, String city, int amount) {}
interface ReportFormat {                                      // the varying steps as a strategy    String header();    String row(Order o);    String totalLine(int total);}
class Exporter {                                              // one class, no subclasses    private final ReportFormat format;
    Exporter(ReportFormat format) {        this.format = format;    }
    String export(List<Order> orders) {        StringBuilder out = new StringBuilder(format.header() + "\n");        int total = 0;        for (Order o : orders) {            out.append(format.row(o)).append("\n");            total += o.amount();        }        return out.append(format.totalLine(total)).append("\n").toString();    }}
class CsvFormat implements ReportFormat {    public String header() { return "id,amount"; }    public String row(Order o) { return o.id() + "," + o.amount(); }    public String totalLine(int total) { return "TOTAL," + total; }}
class ShortTextFormat implements ReportFormat {    public String header() { return "Orders:"; }    public String row(Order o) { return "- " + o.id() + " Rs " + o.amount(); }    public String totalLine(int total) { return "Total Rs " + total; }}
public class StrategyExportDemo {    public static void main(String[] args) {        List<Order> orders = List.of(new Order("A101", "Riya", "Pune", 1799), new Order("A103", "Meena", "Kochi", 2999));        String chosen = "text";                               // could come from the user at runtime        ReportFormat format = chosen.equals("csv") ? new CsvFormat() : new ShortTextFormat();        System.out.print(new Exporter(format).export(orders));        System.out.print(new Exporter(new CsvFormat()).export(orders));    }}
Output
Orders:
- A101 Rs 1799
- A103 Rs 2999
Total Rs 4798
id,amount
A101,1799
A103,2999
TOTAL,4798

What this code does

  • The fixed steps live in Exporter.export, and the varying steps are an object passed to the constructor. This is Strategy: the format can be chosen at runtime, and Exporter is free to extend another class.
  • With Template Method, the format is fixed by which subclass you create. Both designs give the same reports; they differ in how the varying part is plugged in.

Template Method uses inheritance: the variation is a subclass, chosen when you write new CsvExporter(), and the class can extend nothing else. Strategy uses composition: the variation is an object passed in, which can be swapped at runtime and combined with others.

Prefer Strategy when the varying part must change at runtime, when several independent things vary, or when the class already has a parent. Template Method fits when the steps are fixed, the variations are few and stable, and a shared base class is natural.

Find the bug

Spot the template bug

Each snippet has one wrong line. Tap it, then read the fix.

No subclass may skip or reorder the steps.

Round 1 of 2

Next step

Check your understanding

12 quick questions