The Factory Method Pattern is a creational pattern that defines an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
-
Creator: The Creator class declares the factory method, which returns an object of type Product. The Creator class may also define a default implementation of the factory method that returns a default type of Product.
-
ConcreteCreator: The ConcreteCreator class overrides the factory method to return an object of type ConcreteProduct.
-
Product: The Product interface declares the operations that all concrete products must implement.
-
ConcreteProduct: The ConcreteProduct class implements the Product interface.
-
Single Responsibility Principle: The Factory Method Pattern allows you to encapsulate the creation of objects. This means that the Factory Method Pattern can help you adhere to the Single Responsibility Principle, which states that a class should have only one reason to change.
-
Open/Closed Principle: The Factory Method Pattern can help you adhere to the Open/Closed Principle, which states that a class should be open for extension but closed for modification. This means that you can add new products to your application without modifying existing code.
-
Code Reusability: The Factory Method Pattern can help you reuse code by allowing you to create new objects without duplicating code.
-
Complexity: The Factory Method Pattern can introduce complexity to your codebase, especially if you have many different types of products.
-
Duplication: The Factory Method Pattern can lead to duplication of code if you have many different factories that create similar products.
-
When you want to encapsulate the creation of objects.
-
When you want to adhere to the Single Responsibility Principle.
-
When you want to adhere to the Open/Closed Principle.
-
When you want to reuse code by creating new objects without duplicating code.
Check out the src directory for an example of the Factory Method Pattern in action.