Simple Factory Pattern
The Simple Factory encapsulates the object creation process in a single method and doesn’t involve inheritance. It’s a basic implementation where a class contains a method for creating instances of other classes. This method typically takes parameters to decide which instance to create.
Here is an example in C#:
|
|
Factory Method Pattern
The Factory Method Pattern involves a method in a base class which is overridden by subclasses to create specific instances. This pattern uses inheritance and relies on subclasses to handle the instantiation of objects.
Here is the example in C#:
|
|
Let’s Compare the Two Approaches
- Inheritance:
- In the Simple Factory, we use a single class with a static method. It doesn’t involve inheritance.
- In the Factory Method, we use inheritance. The base class defines a factory method and subclasses override it to create specific instances.
- Flexibility and Extensibility:
- In the Simple Factory, adding a new product requires modifying the factory class, which may violate the Open/Closed Principle.
- In the Factory Method, adding a new product involves creating a new subclass. The base class doesn’t need to change, adhering to the Open/Closed Principle.
- Responsibility:
- In the Simple Factory, the method is responsible for deciding which class to instantiate based on parameters.
- In the Factory Method, the decision of which class to instantiate remains in the subclasses.
Sources For More Reading
- “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Gang of Four)
- Microsoft Docs—Factory Method
- Refactoring Guru—Factory Method
These examples and explanations should enrich your understanding of both patterns and their differences.
The Factory Method Pattern is the one that we use the most in software development, but you’ll see or use the Simple Factory for time to time.
The Factory Method may look like overkill in terms of boilerplate code you need.
Depending on your codebase and size of the project, you may prefer one method over the other.
Adhering to the Open/Closed Principle may guide your choice.
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.