Factory Method Pattern
The Factory Method pattern is a creational design pattern that defines an interface for creating objects, but allows subclasses to alter the type of objects that will be created. It provides a way to delegate the instantiation logic to child classes.
As per the Gang of Four definition,##new_line####new_line##"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”
Implementation
The main components of the Factory Method pattern are the Creator, the ConcreteCreator, the Product, and the ConcreteProduct.
- The Creator is an abstract class that defines a factory method, which returns an object of the Product class.
- The ConcreteCreator is a subclass of the Creator, which implements the factory method and returns an instance of a ConcreteProduct.
- The Product is an abstract class that defines the interface for the object that will be created by the factory method.
- The ConcreteProduct is a subclass of the Product class and provides a concrete implementation of the interface defined by the Product class.
Here is an example of Factory Method Pattern:
In this example, the Superhero
class is the Product, and the Superman
and Spiderman
classes are the ConcreteProduct. The SuperheroFactory
class is the ConcreteCreator and the create_superhero
method is the factory method, which is an interface for creating objects.
You can create your Superhero like this:
Use Cases
A use case for the Factory Method pattern is when a class can't anticipate the type of objects it needs to create. Instead of specifying the type of object to create, the Factory Method pattern allows the class to specify a factory method that will create the object. This allows for more flexibility in the types of objects that can be created, as different factory methods can return different types of objects.