Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Suppose a text editor wants to manipulate (save, load, etc.) documents without knowing they types: JSON, XML, text, etc.
How can to create a new document without knowing its concrete type?
a class cannot 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.
defines the interface of objects the factory method creates.
implements the Product interface.
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.
the code may become more complicated: introduces a lot of new subclasses
overrides the factory method to return an instance of a ConcreteProduct.
The code only deals with the Product interface: eliminates the need to bind application-specific classes into your code.
Provides hooks for subclasses.
Connects parallel class hierarchies.
Two variants:
the Creator class is an abstract class and does not provide an implementation for the factory method
the Creator is a concrete class and provides a default implementation for the factory method
Parameterized factory methods.
«Design Patterns: Elements of Reusable Object-Oriented Software.» Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides. Addison Wesley. October 1994.