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

