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.










