Factory Method
13 Mar 2022Intent
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.
Also known as
Virtual Constructor.
Applicability
Use the factory method when:
- A class can't anticipate the class of objects it must create.
- A class wants it's subclasses to specify the objects it creates.
- Classes delegate responsibility to one of the several helper subclasses, and you want to localize the knowledge of which subclass is the delegate.
Structure
Participants
- Product: defines the interface of objects that factory method creates.
- Concrete Product: implements the Product interface.
- Creator: declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory methods that returns a default ConcreteProduct object. Creator may call the factory method to create a Product object.
- ConcreteCreator: overrides the factory method to return an instance of ConcreteProduct.
Collaborations
Creator relies on it's subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Consequences
- Factory method eliminate the need to bind application-specific classes into your code.
- Provides hooks for subclasses.
- Connects parallel class hierarchies.
Sample Code
Related Patterns
- Abstract Factory is often implemented with Factory method.
- Factory methods are usually called within Template Methods.
- Prototypes don't require subclassing Creator. However, they often require an Initialize operation on the Product class. Creator uses Initialize to initialize the object. Factory Method doesn't require such an operation.