Template Method Pattern

The Template Method pattern: fixing the order of an algorithm's steps in a base class and letting subclasses supply the steps that differ.

  • 9 cards
  • 4 questions
  • About 18 min
  • Intermediate to Advanced
Share

Every report is loaded, formatted and saved; every import is opened, parsed, validated and stored; every test is set up, run and torn down. The order never changes, and only one or two steps differ from one case to the next. The Template Method pattern writes the order once, in a method of a base class, and lets each subclass supply the steps that differ.

This topic opens on that sequence copied into every class, then reads the participants off the class diagram and separates the steps a subclass must write from the hooks it may override. The template runs the same sequence for two subclasses in Python, Java and TypeScript, and shows how each language protects the fixed order.

Two examples follow: an importer for CSV and JSON files, and Python's own unittest.TestCase, which calls your setUp, test and tearDown in an order you never write. A comparison passes the varying steps as functions instead of subclassing. The gotcha is a subclass that overrides the template method itself, and the exercise finds every part of the pattern in a game loop.

By the end you can recognise a template method, write one with abstract steps and hooks, and find it in a framework.

Contents

9 cardsnot started