CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 3 of 6 · 2 min read

The structure

Template, steps and hooks.

An AbstractClass holds the template method and declares the steps. ConcreteClasses fill in the steps. A report generator shows it.

abstract class Report {
    public final String generate(List<String> rows) {          // template method
        StringBuilder sb = new StringBuilder();
        sb.append(header()).append('\n');
        for (String r : rows) sb.append(formatRow(r)).append('\n');
        if (wantsFooter()) sb.append(footer(rows.size())).append('\n');
        return sb.toString();
    }

    protected abstract String header();                          // must override
    protected abstract String formatRow(String r);               // must override
    protected boolean wantsFooter() { return false; }            // hook
    protected String footer(int n) { return "total " + n; }
}

class TextReport extends Report {
    protected String header() { return "USAGE"; }
    protected String formatRow(String r) { return "- " + r; }
    @Override protected boolean wantsFooter() { return true; }
}

class CsvReport extends Report {
    protected String header() { return "room,hours"; }
    protected String formatRow(String r) { return r.replace(' ', ','); }
}

With the rows "A1 8" and "B2 3", TextReport produces the lines USAGE, "- A1 8", "- B2 3" and "total 2". CsvReport produces "room,hours", "A1,8" and "B2,3", with no footer.

Three kinds of method appear. The template method generate is final, so no subclass can change the order. The abstract steps header and formatRow must be supplied. The hook wantsFooter has a default body that subclasses may override. GoF says a hook often does nothing by default, and that it is important to state which operations are hooks and which are abstract, so subclass writers know what the class is designed to let them change.

GoF calls the control flow an inverted structure and names it the Hollywood principle, after the studio habit of telling applicants to wait for a call. The parent calls the subclass's methods, and the subclass does not call the parent's algorithm. HF turns this into a design principle: high-level components call low-level ones, and low-level ones do not call back up into the high-level logic, which prevents tangled dependencies.

Hook

A hook is a method in the parent class with a default body, that subclasses may override to change a step or add one.

Example: wantsFooter(), which returns false unless a subclass says otherwise.

Check yourself: 1. What does CsvReport print for the row "B2 3"? 2. Why is generate marked final? 3. What is the difference between an abstract step and a hook?