Card 02/ 09

ConceptDifficulty: Intermediate1 min

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.

Factory Method participants
Each participant and its role
ParticipantRole
ProductThe interface every created object implements. The creator only ever uses this type.
ConcreteProductA class that implements Product. There is one for each kind of object the program can create.
CreatorDeclares factory_method, which returns a Product, and contains the shared code, here some_operation, that calls it.
ConcreteCreatorOverrides 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.