liveBook · Manning

Factory

As explained in Object-Oriented Software Design in C++

A class responsible for creating and selecting instances of other classes while hiding construction details from clients.

A factory encapsulates object creation so clients depend on a common interface instead of hardcoded concrete classes. A factory function receives a parameter, selects a subclass, and returns the resulting object at run time. section 7.4 section 7.6

A factory improves a design by:

  • Hiding calls to new and construction details from client code. section 7.4
  • Allowing one interface, such as Toy, to represent different concrete objects. section 7.4
  • Moving creation responsibility into a related factory class or into subclasses through Factory Method. section 9.1.3
  • Supporting extension with less coupling, fewer hardcoded behaviors, and stable client classes. section 9.1.3

Toys and athletic departments

ToyFactory::make(kind) returns a ToyCar, ModelAirplane, or TrainSet according to Kind. In the Factory Method design, AthleticsDept delegates create_sport() to VarsityDept and IntramuralDept, which create category-specific Sport objects while the shared reporting logic remains stable. section 7.4 section 9.1.3

Figure 9.2 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.

Shows subclasses acting as factory classes and delegating creation to category-specific implementations. section 9.1.3

How Object-Oriented Software Design in C++ covers it

How deep it goes
Explains parameterized factory functions and Factory Method delegation, but does not develop broader factory variants.
Examples
Uses ToyFactory with cars, airplanes, and trains, then AthleticsDept subclasses creating varsity and intramural sports.
What it assumes
Assumes familiarity with inheritance, superclass interfaces, subclasses, and runtime object creation.
What you can do after
Builds factory functions or subclass-based Factory Methods that select concrete objects while keeping clients stable.
How it connects
Connects factories with Code to the Interface, composition over inheritance, delegation, Open-Closed, and Single Responsibility principles.

Also explained in

Compare how 11 books explain factory →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.