The third creational pattern we will study is the Factory Method one.
By definition a Factory Method is any method whose responsibility is creating an object, or providing a already existent instance of a particular class.
Factory Methods are the seams which allow tuning of an instantiation; for example, to recycle already created objects or to introduce subclasses of the original Product.
This pattern has a strong affinity with the Abstract Factory one: usually every relevant method of the Abstract Factory is a Factory Method, but isolated Factory Methods can be used also in other situations. For instance, with the intention of having them overridden by subclasses, incorporating the factory in the class itself and having them called by Template Methods.
Factory Methods may be moved out of their class in subsequent refactorings and evolve in an external Abstract Factory.
- Product: the abstraction of the created object.
- ConcreteProduct: a subclass or implementation of Product.
- Creator: the base class, which declares an abstract or default Factory Method.
- ConcreteCreator: a subclass of the Creator which overrides the Factory Method to return a ConcreteProduct.
A common misconception is a static version of the Factory Method, which is placed on a Product or ConcreteProduct class and provide a constructor with a fancy name. The original intent was having the method overridden, so if it is implemented as static the goal is not achieved; the trick is that the method should reside on the class that need the instantiation of Product objects, and not on the Product itself.
Some versions even propose to maintain a static object pool managed by a static method in the Product class, which is dangerously-equivalent to filling some water bottles with gasoline and amassing them in the car trunk just in case the tank needs to be refilled, throw in a burning match and closing the trunk with the keys inside.
Moreover, if the method has references to the subclasses of Product, they become all mutually coupled and depend the one on all the others, forcing to modify the base class in case a new subclass is added.
In conclusion, a Factory Method is a non-static overridable creation method, which belongs to the class that needs to instantiate a Product (or to a class composed by it).
Remember to comment and propose patterns for inclusion in this series!