liveBook · Manning

Factory

As explained in Software Design for Python Programmers

A factory function is a function that encapsulates creating and returning objects, often selecting among subclass types based on an input value.

A factory function encapsulates object creation and returns an object selected at run time. A parameter commonly chooses among subclass instances sharing a common supertype, replacing hardcoded construction with a flexible creation point. section 7.4 section 7.6

Use a factory when direct construction creates change leaks:

  • Identify the common interface or superclass that callers need. section 7.4
  • Move subclass construction into a function, a static method, or a dedicated factory class. section 7.4
  • Pass the type or selection value at runtime, allowing callers to use different implementations without changing their construction logic. section 7.4
  • For larger designs, let specialized subclasses create objects through factory methods while the stable superclass delegates creation. section 9.1.3

Toy factory

A hardcoded `toy = TrainSet(...)` fixes the variable to one implementation. A factory instead accepts the selected class: `class ToyFactory:\n @staticmethod\n def make(toy_type, play, sound):\n return toy_type(play, sound)`. Calling `ToyFactory.make(toy_class, play, sound)` can create a toy car, model airplane, or train set while the caller retains one construction interface.

How Software Design for Python Programmers covers it

How deep it goes
Defines the principle, demonstrates a Python implementation, and extends it to Factory Method while stopping short of broader implementation detail.
Examples
Demonstrates toy cars, model airplanes, and train sets, then applies Factory Method to varsity and intramural sports.
What it assumes
Assumes familiarity with classes, inheritance, and common supertypes while reinforcing runtime polymorphism and object-creation responsibility.
What you can do after
Apply it via Python functions or classes to remove hardcoded construction and vary object types at runtime.
How it connects
Connects runtime polymorphism with subclassing, composition, Code to the Interface, delegation, and the Open-Closed Principle.

Also explained in

Compare how 11 books explain factory →

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.