AlgoViz

Template method pattern

medium 50 min

Template method writes the order of an algorithm once, in a base class, and leaves some steps open for subclasses.

Watch lesson4:38

Where it shows up

The same pattern appears across everyday software.

  • Java AbstractList

    A skeletal list. For an unmodifiable list the documentation asks for `get` and `size` only, the rest is built on them.

  • HttpServlet

    A subclass overrides at least one method, usually `doGet`, `doPost`, `doPut` or `doDelete`. `service` dispatches the request to them.

  • Spring AbstractController

    Its documentation names the pattern. Subclasses implement `handleRequestInternal`, the base runs the common workflow first.

  • Python unittest

    The runner calls `setUp`, the test method and `tearDown`. You fill them, you do not call them.

  • Python socketserver

    `handle_request` calls `get_request`, `verify_request` and `process_request`. `verify_request` is a hook that returns a Boolean.

  • Python html.parser

    Subclass `HTMLParser` and override handlers such as `handle_starttag`. The parser decides when they run.

  • Java ThreadPoolExecutor

    `beforeExecute`, `afterExecute` and `terminated` are hooks around each task.

  • AbstractQueuedSynchronizer

    Locks are built by filling in `tryAcquire`, `tryRelease` and others. Queueing is done by the base class.

  • Android Activity

    The system calls `onCreate`, `onStart`, `onResume` and the others as the lifecycle moves.

  • Django class-based views

    `View.dispatch` hands the request to `get`, `post` and others that your subclass defines.

  • Maven

    The build lifecycle has a fixed order of phases, and plugins bind goals to them. The same idea without inheritance.

  • React class components

    React calls `shouldComponentUpdate`, `render` and `componentDidUpdate`. React's documentation now recommends function components.