CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 2 of 6 · 1 min read

The idea

A fixed outline with blanks.

Think of a recipe card for hot drinks: boil water, brew, pour into a cup, add extras. Tea and coffee follow the same four steps. Only "brew" and "add extras" differ. The order sits on the card once, and each drink fills in its own steps.

GoF's intent for Template Method is to fix the outline of an algorithm inside one operation and hand some steps to subclasses, so they can redefine those steps while the order stays untouched. GoF says to use it to write the unchanging parts once and leave the varying behaviour to subclasses, to pull common behaviour out of several subclasses so it is not duplicated, and to control which points subclasses may extend.

HF reaches it from two recipes, tea and coffee, that were written as separate classes with similar code. The common steps were pulled up into an abstract parent. This is the duplication cure of Level 2, module 7, done by inheritance.

Template method

A template method is a method in a parent class that fixes the order of an algorithm's steps and calls other methods for the steps that subclasses supply.

Example: generate() in a report class, which calls header(), formatRow() and footer().

Check yourself: 1. What stays fixed and what varies in the recipe card? 2. Which kind of duplication does Template Method remove?