Card 09/ 09
Recap: Factory Method Pattern
A method the subclass overrides to choose the class, so the base code never names it.
Factory Method puts the choice of which class to create behind one method that subclasses override.
- Intent. Define an interface for creating an object, and let subclasses decide which class to instantiate.
- Participants. The creator declares the factory method and contains the shared code that calls it; each concrete creator overrides it to return one concrete product; every product shares the
Productinterface. - Recognise it by shape. An overridable method that returns an object through an interface, called by code in the base class. The creator usually has a domain name, such as
OrderNotifierorCollection, not "Factory". - In the wild. Java's
Collection.iterator(): each collection returns its own private iterator class, and the for-each loop never names it. - In Python. Passing a class or a callable replaces the subclass when creation is the only thing that varies.
- Its cost. Two parallel hierarchies. With only one product, the pattern protects nothing; name the second product before adding it.
← → move through sections and cards