Card 02/ 09
Factory Method Pattern Structure: The Class Diagram
Creator, ConcreteCreator, Product and ConcreteProduct, and the one method that joins them.
Factory Method has four participants, two on each side of one method. The creator side declares and overrides the factory method; the product side is what that method returns. This card reads each participant's role off the Gang of Four's class diagram, so you can find them in any implementation.
| Participant | Role |
|---|---|
| Product | The interface every created object implements. The creator only ever uses this type. |
| ConcreteProduct | A class that implements Product. There is one for each kind of object the program can create. |
| Creator | Declares factory_method, which returns a Product, and contains the shared code, here some_operation, that calls it. |
| ConcreteCreator | Overrides factory_method to return one particular ConcreteProduct. |
Two hierarchies run side by side, and they line up: each concrete creator is paired with the concrete product it makes. The dashed dependency from Creator to Product points at the interface, which is the point of the pattern. Only the concrete creators, at the bottom of the diagram, depend on concrete products.
The factory method in the diagram is abstract, drawn in italics, so every subclass must override it. That is the usual form, but not the only one. A creator can give the method a default body that returns a common product, and then a subclass overrides it only when it needs something else.
The pattern is named for the method, not for a class. Nothing called "factory" needs to exist: the creator is an ordinary class, often with a domain name such as OrderNotifier or Editor, that happens to delegate one decision.
← → move through sections and cards