Card 09/ 09

RecapDifficulty: Advanced1 min

Recap: Template Method Pattern

The base class owns the order, and subclasses own the steps.

Template Method writes an algorithm's order once, in a base class, and leaves the varying steps to subclasses.

  • Intent. Define the skeleton of an algorithm in one method, deferring some steps to subclasses.
  • Three kinds of method. The template method, which subclasses must not override; abstract steps, which they must write; hooks, which they may override.
  • Direction of control. The base class calls the subclass, the Hollywood principle.
  • In the wild. unittest.TestCase.run, which calls setUp, the test and tearDown.
  • In Python. Pass the varying steps as functions when there are few and they share no state.
  • The trap. A subclass that overrides the template method and skips a step; Java's final stops it, and in Python a type checker reads typing.final.
  • When not. Steps chosen at run time, or subclasses that would override most of the skeleton.