Overview

8 The Template Method and Strategy Design Patterns

This chapter explains how two industry-proven design patterns—Template Method and Strategy—help structure applications that must manage multiple algorithms. Rather than being drop-in code, patterns are reusable models you tailor to your problem. Using a sports domain, the chapter contrasts baseline implementations with pattern-based refactorings, showing how to eliminate duplication, improve clarity, and make behavior easier to extend and modify over time.

Template Method addresses algorithms that follow a fixed sequence of steps where some steps are shared and others vary. The chapter starts with duplicated report-generation logic for different sports and then refactors to an abstract superclass that defines the workflow while implementing common steps (like headers and footers) and delegating variable steps (data acquisition, analysis, and report body) to subclasses. The result is a clear algorithm outline, reduced duplication, adherence to the Open-Closed Principle, and better encapsulation of what changes, all while preserving the required order of operations.

Strategy targets families of interchangeable algorithms that should be swappable at runtime. The initial inheritance-based approach hardcodes player-recruitment and venue-reservation behaviors and repeats logic. The refactoring composes a sport from independent strategy objects (player and venue), enabling reuse (e.g., a shared stadium strategy), runtime flexibility (swap a venue on the fly), and looser coupling. The chapter closes with guidance: use Template Method when a stable workflow needs step-level customization via inheritance, and use Strategy when you must switch entire algorithms via composition to keep clients independent from algorithm variants.

The public method generate_report() of class BaseballReport calls its private methods that perform the steps to generate a baseball game report. It depends on class BaseballData to generate random test data for the report.
The public method generate_report() of class VolleyballReport calls its private methods, which perform the steps to generate a volleyball game report. It depends on class VolleyballData to generate random test data for the report.
This version of the application is modeled from the Template Method Design Pattern. The abstract superclass GameReport outlines the steps in the proper order for the algorithm to generate a report. It implements the common steps _print_header() and _print_footer() and delegates the remaining steps _acquire_data(), _analyze_data(), and _print_report() to the BaseballReport and VolleyballReport subclasses. The public template method generate_report() in the superclass calls the step methods in the proper order. The grayed-out portions of the diagram haven’t changed logically from figures 8.1 and 8.2.
The generic model of the Template Method Design Pattern. We can compare it with figure 8.3. The methods of the abstract superclass AlgorithmOutline outlines the steps of the algorithm. Method template_method() calls the methods representing the steps in the correct order. The superclass implements the common steps and delegates implementing the varying steps to its concrete subclasses. Table 8.1 shows how the example application applies the pattern.
The first version of our sports application. Superclass class Sport has abstract methods representing algorithms that each of the subclasses Baseball, Football, and Volleyball must implement to recruit players and reserve a venue.
This version of the application is modeled from the Strategy Design Pattern for the sport teams and venues. The player family of algorithms implement the PlayerStrategy interface, and the venue family of algorithms implement the VenueStrategy interface. Class Sport uses has-a relationships to aggregate the algorithms. Each player and venue algorithm has a strategy() method. The Baseball, Football, and Volleyball subclasses are now much simpler, and each one sets the _SPORT_TYPE, _player_strategy and _venue_strategy instance variables of the Sport superclass.
The generic model of the Strategy Design Pattern. Compare to figure 8.6. Table 8.2 shows how the example application applies the pattern.

Summary

  • The Template Method Design Pattern defines the skeleton or outline of an algorithm and defers the implementation of some of the steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  • The Template Method Design Pattern relies on inheritance, the is-a relationship.
  • The Strategy Design Pattern encapsulates each algorithm in a family of algorithms and makes them interchangeable. At run time, an application can choose which algorithm to use.
  • The Strategy Design Pattern uses composition, the has-a relationship. The client class is loosely coupled from the strategy subclasses.

FAQ

What problem does the Template Method pattern solve in the chapter’s report example?The Template Method pattern solves duplicated and scattered algorithm steps when multiple reports share the same overall workflow but differ in some steps. In the chapter, both BaseballReport and VolleyballReport follow the same sequence—print header, acquire data, analyze data, print report, print footer—but parts of the implementation vary. By moving the skeleton (generate_report) and common steps (_print_header, _print_footer) into an abstract superclass (GameReport) and deferring variable steps (_acquire_data, _analyze_data, _print_report) to subclasses, the design removes duplication and keeps the algorithm order consistent.
How is the Template Method implemented in Python in this chapter?GameReport is an abstract base class (inherits from abc.ABC). It implements the template method generate_report(), which calls the steps in order: _print_header(), _acquire_data(), _analyze_data(), _print_report(), _print_footer(). The varying steps are marked with @abstractmethod so subclasses (BaseballReport, VolleyballReport) must implement them. The shared steps (_print_header and _print_footer) are implemented in GameReport.
Which steps are common versus varying in the report-generation algorithm?Common steps: printing the header and footer are shared across reports and live in GameReport as _print_header() and _print_footer(). Varying steps: acquiring data, analyzing data, and printing the body of the report differ by sport and are implemented in subclasses as _acquire_data(), _analyze_data(), and _print_report().
What benefits did applying the Template Method bring to the report code?- A single algorithm outline in GameReport ensures a fixed order of steps. - Reduced duplication: common code (generate_report, header/footer printing) is centralized. - Open-Closed Principle: GameReport stays closed to modification while new report types extend it. - Encapsulate What Varies: each subclass isolates its sport-specific steps. - Cohesion and low coupling among report subclasses.
What problem does the Strategy pattern address in the sports example?Strategy addresses managing a family of interchangeable algorithms (player recruitment and venue reservation) that should be selected and swapped at runtime. Instead of hardcoding logic inside each sport subclass, the design encapsulates each algorithm as a strategy object and composes a Sport with the strategies it needs.
How does Strategy enable runtime flexibility in the chapter’s code?Sport holds references to two strategy interfaces—player_strategy and venue_strategy—and delegates recruit_players() and reserve_venue() to their strategy(). Because these are regular attributes with setters, the application can replace them at runtime. For example, a Volleyball instance can switch its venue strategy from OpenField to Stadium without changing the Sport or Volleyball classes.
How are the strategies organized and plugged into Sport?Two interfaces (abstract base classes) define the contracts: PlayerStrategy and VenueStrategy, each exposing a strategy() method. Concrete strategies like BaseballPlayers, FootballPlayers, VolleyballPlayers implement PlayerStrategy; Stadium and OpenField implement VenueStrategy. Sport receives strategy instances in its constructor (composition/aggregation) and delegates calls to them, following “code to the interface.”
How do I add a new sport or change an algorithm using Strategy?- Add a new sport: create a subclass of Sport (or even use Sport directly) and pass appropriate PlayerStrategy and VenueStrategy instances in its constructor. No changes to Sport are needed (Open-Closed Principle). - Change or add an algorithm: implement a new concrete strategy class (e.g., IndoorArena implements VenueStrategy) and supply it to any Sport instance, even dynamically at runtime.
When should I choose Template Method versus Strategy?- Choose Template Method when multiple variants share a fixed overall workflow and you want the superclass to enforce order and provide common steps, with subclasses overriding specific parts. It relies on inheritance (is-a). - Choose Strategy when you need to swap whole algorithms at runtime, share them across clients, and evolve them independently. It relies on composition (has-a) and keeps the client loosely coupled to the algorithms.
Are there trade-offs to using these patterns?Yes. Template Method ties variants to an inheritance hierarchy, which can be rigid if variation spans more than a few steps. Strategy adds more classes and interfaces, which can feel heavier in very small systems, but it pays off with reuse, runtime swapping, and independent evolution of algorithms. The chapter even notes that Strategy increases class count in the small example, but the benefits become clear as behaviors grow.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Software Design for Python Programmers ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Software Design for Python Programmers ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Software Design for Python Programmers ebook for free