Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Applicability
Use the Factory Method pattern when
a class can’t anticipate the class of objects it must create.
a class wants its subclasses to specify the objects it creates.
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Structure
Members
Product Interface
All products will implement this inteface so that any classes that need to use products will refer to this interface instead of referring the concrete product class.
ConcreteProducts
Concrete products that implement the Product interface.
ConcreteFactories
Overrides the factory method to return an instance of a ConcreteProduct.
Creator
Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
May call the factory method to create a Product object.
Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Outcome
Factory methods eliminate the need to bind application-specific classes into your code. The code only deals with the Product interface; therefore it can work with any user-defined ConcreteProduct classes.
A potential disadvantage of factory methods is that clients might have to subclass the Creator class just to create a particular ConcreteProduct object. Subclassing is fine when the client has to subclass the Creator class anyway, but otherwise the client now must deal with another point of evolution.
Leave A Comment