Overview

9 The Factory Method and the Abstract Factory Design Patterns

This chapter explains how to make Python applications more flexible by delegating object creation to “software factories” at runtime. It introduces two creational design patterns—Factory Method and Abstract Factory—and develops them incrementally through a sports scheduling example. The narrative emphasizes core design principles such as Encapsulate What Varies, the Open-Closed Principle, Single Responsibility, Delegation, and the Principle of Least Knowledge, showing how these patterns reduce coupling and localize change.

Factory Method is applied first to address brittle, error-prone code that decided which concrete sport to create with long conditional logic. The solution makes AthleticsDept an abstract creator with a factory method (create_sport), and moves instantiation into concrete creators VarsityDept and IntramuralDept. This shift encapsulates object construction, shortens decision logic, and lets the common reporting workflow remain stable while subclasses add or vary concrete sports. The result is clearer responsibilities, easier extensibility (e.g., adding a ClubDept), and looser coupling between the department classes and the concrete Sport implementations.

Abstract Factory extends the design when consistency across families of related objects matters—in this case, ensuring varsity player and venue objects are never mixed with intramural ones. A ProvisionsFactory interface is introduced, with VarsityFactory and IntramuralFactory producing the appropriate player and venue strategies. Sport receives a factory and delegates creation of its provisions, keeping families coherent, enabling runtime selection of the desired family, and further localizing changes. The chapter closes by contrasting the patterns: use Factory Method to let subclasses decide which single product variant to create; use Abstract Factory when you must create and keep multiple related products consistent as a family.

Class AthleticsDept generates the report for varsity and intramural sports. The grayed-out portions of the diagram haven’t changed logically from figure 8.6.
This version of the application is modeled from the Factory Method Design Pattern. Superclass AthleticsDept delegates creating Sport objects to its subclasses. Subclasses VarsityDept and IntramuralDept are factory classes. Each implements the factory function create_sport() which creates and returns an appropriate varsity or intramural Sport object. The grayed-out portions of the diagram have not changed logically from figure 9.1.
The generic model of the Factory Method Design Pattern. Compare to figure 9.2. Table 9.1 shows how the example application applies the pattern.
This version of the application is modeled from the Abstract Factory Design Pattern. Interface ProvisionsFactory is the abstract factory whose implementor classes are used by the Sport subclasses. Implementor class VarsityFactory creates the varsity family of player and venue objects, and therefore, VarsityDept uses VarsityFactory. Implementor class IntramuralFactory creates the intramural family of player and venue objects, and therefore, IntramuralDept uses IntramuralFactory. The grayed-out portions of the diagram have not changed logically from figure 9.2.
The generic model of the Abstract Factory Design Pattern. Compare with figure 9.4. Table 9.2 shows how the example application applies the pattern.

Summary

  • The Factory Method Design Pattern defines an interface for creating an object but delegates to subclasses to decide which object to create.
  • The Abstract Factory Design Pattern provides an interface for creating families of related objects. It helps to prevent coding errors that mix up objects from different families.

FAQ

What problem does the Factory Method pattern solve in this chapter’s example?The Factory Method encapsulates object creation so the client doesn’t decide concrete classes. In the sports example, AthleticsDept defines an abstract create_sport(), and its subclasses VarsityDept and IntramuralDept decide which Sport subclass to instantiate. generate_report() stays unchanged and delegates creation to create_sport().
What issues existed before applying Factory Method?- Long, error‑prone match statements to pick a concrete Sport
- AthleticsDept had multiple responsibilities (create objects and generate reports)
- Tight coupling to concrete Sport classes
- Hard to add new sports or categories without editing existing code
How does Factory Method improve extensibility and maintainability?- Encapsulates what varies: object creation moves to subclasses
- Supports the Open–Closed Principle: add a new department (e.g., ClubDept) by subclassing without changing AthleticsDept
- Shorter, focused match logic inside each factory subclass
- Looser coupling between report generation and concrete Sport classes
What is the Abstract Factory pattern and when do I need it here?Abstract Factory creates families of related objects without exposing concrete classes. Use it when multiple related products must be created together and must not be mixed, e.g., varsity players with the varsity venue (and not intramural ones) for a given Sport.
How is Abstract Factory implemented in the example?- ProvisionsFactory defines make_players() and make_venue()
- VarsityFactory and IntramuralFactory implement those methods for their families
- The department’s create_sport() passes the appropriate factory into the Sport constructor
- Sport uses the factory to obtain the correct PlayerStrategy and VenueStrategy for its family
How does the architecture prevent mixing objects from different families?Each department uses only its matching factory (VarsityDept → VarsityFactory, IntramuralDept → IntramuralFactory). Sport delegates to that factory to build both the player and venue strategies, ensuring the pair always comes from the same family.
How do I add a new sport or a new category with these patterns?- New sport type (e.g., BASKETBALL): add enum value, create a Sport subclass with the right _SPORT_TYPE, and update the relevant factory method(s) to return the right players/venue for that sport.
- New category (e.g., Club): add a new Dept subclass implementing create_sport(), add a new concrete ProvisionsFactory for that family, and wire it by passing the new factory to Sport.
How do these patterns relate to the Strategy pattern used in the chapter?Strategy encapsulates behavior (players and venues are strategies). Factory Method and Abstract Factory decide which concrete strategies to use. With Abstract Factory, Sport receives a factory and asks it to create the appropriate PlayerStrategy and VenueStrategy for its family.
What are the GoF roles mapped to the example?- Factory Method: Creator → AthleticsDept; ConcreteCreator → VarsityDept, IntramuralDept; Product → Sport; ConcreteProduct → VarsityBaseball, IntramuralFootball, etc.
- Abstract Factory: AbstractFactory → ProvisionsFactory; ConcreteFactories → VarsityFactory, IntramuralFactory; AbstractProducts → PlayerStrategy, VenueStrategy; ConcreteProducts → VarsityBaseballPlayers, Stadium, etc.
How do I choose between Factory Method and Abstract Factory?- Use Factory Method when you need one product with varying concrete types and want to defer the choice to subclasses.
- Use Abstract Factory when you must create multiple related products together and prevent cross‑family mixing.
- In the chapter: Factory Method selects which Sport to build; Abstract Factory ensures its players and venue come from the same family.

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