Also know as Virtual constructor.
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but let subclasses decide the type of objects that will be created.
It provides an encapsulation to objects instanciation and can therefore be seen as a wrapper to the new keyword.
It allows to hide the business logic behind the objects creation and build it into the factory instead of distributing it all around the code base.
In the end, the client knows about the abstract class but not the concrete subclass - this is the subclass that decides which class to instantiate on run-time.
Participants
- Product Interface for the objects the Factory method can create.
- Product1 Implements the Product interface.
- Creator Declares the factory method (can also provide a default implementation) returning a Product object.
- Creator1 Implements the factory method to return the right Product type.
Some more explanations
- The Creator class that requires a Product object doesn't instantiate the Product1 class directly. Instead, the Creator refers to a separate factoryMethod() to create a product object, which makes the Creator independent of which concrete class is instantiated.
In this example, the Creator1 subclass implements the abstract factoryMethod() by instantiating the Product1 class.
Note : Example taken from here
Pros
As stated here, the Factory method is a way of circumventing some C++ constructor limitaions :
- No return type
- Naming
- Compile time bound
- There is no virtual constructor
It provides a good solution in the following cases :
- The client wants to delegate the decision of the type of object to create.
- The client does not know the actual class from which subclass to create the object.
Cons
The Factory Method pattern can expand the total number of classes in a system. Every concrete Product class also requires a concrete Creator class. The parameterized Factory Method avoids this downs.
- The Factory method is closely related to Abstract factory and Prototype patterns.
- A Youtube video clearly illustrating this concept.
- An interesting brief article on the subject.