liveBook · Manning

Template method design pattern

As explained in Software Design for Python Programmers

The Template Method pattern defines an algorithm's fixed-order skeleton in a superclass while allowing subclasses to implement selected variable steps.

Use the Template Method pattern when an algorithm must follow a prescribed order while some steps vary between implementations. A superclass owns the algorithm’s skeleton and common behavior; subclasses implement the variable steps. section 8.1 section 8.4

Generating sports reports

A GameReport superclass can define generate_report() as the template method: it prints the header, acquires data, analyzes it, prints the report, and prints the footer. BaseballReport and VolleyballReport implement _acquire_data(), _analyze_data(), and _print_report() for their own report formats. Shared header, footer, and ordering live in one place, eliminating duplicated workflow while preserving each sport’s specialized behavior. section 8.1.3

Apply the pattern by separating the algorithm’s stable and variable responsibilities:

  • Define an abstract superclass that names the algorithm’s steps. section 8.1.3
  • Implement common steps in the superclass. section 8.1.3
  • Implement varying steps in cohesive subclasses. section 8.1.3
  • Choose Template Method when inheritance fits; choose Strategy when whole algorithms should be interchangeable through composition. section 8.3
Listing 8.6 (Program 8.2 Reports-TemplateDP): game_report.py
from abc import ABC, abstractmethod

class GameReport(ABC):
    def __init__(self, title):
        self._title = title

    def _print_header(self):    #1
        print(self._title)
        print()

    def _print_footer(self):    #1
        print()
        print('End of report')

    @abstractmethod
    def _acquire_data(self): pass    #2

    @abstractmethod
    def _analyze_data(self): pass    #2

    @abstractmethod
    def _print_report(self): pass    #2

    def generate_report(self):    #3
        self._print_header()
        self._acquire_data()
        self._analyze_data()
        self._print_report()
        self._print_footer()

Inspect the compact Python implementation showing the abstract superclass, common steps, abstract variable steps, and ordered template method. section 8.1.3

How Software Design for Python Programmers covers it

How deep it goes
Explains the pattern through sports-report code, superclass responsibilities, subclass variation, benefits, and comparison with Strategy.
Examples
Uses baseball and volleyball game reports, with shared headers and footers and sport-specific acquisition, analysis, and printing.
What it assumes
Assumes basic object-oriented inheritance and introduces the pattern through concrete Python report classes.
What you can do after
Build it from scratch by modeling a shared algorithm in a superclass and delegating selected steps to subclasses.
How it connects
Connects inheritance, abstract superclasses, subclasses, code duplication, the Open-Closed Principle, and Strategy.

Also explained in

Compare how 2 books explain template method design pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.