Mastering the Art of the Factory Method Design Pattern
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be?created.
in other words, it defines an interface for creating an object, but leaves the choice of its type to the subclasses, creation being deferred at run-time.
so the main Usage is to create objects without specifying the exact class of object that will be created.
it addresses the problem when adding a new class to the program isn’t that simple if the rest of the code is already coupled to existing?classes.
The Factory Method pattern recommends using a special factory method instead of directly creating objects with the new operator. This method still uses the new operator internally to create objects and the objects it returns are called products.
so it did solve the problem by letting You customize the factory method in a subclass to create different types of products by changing the class of the products being created.
the main Advantages are:
- Encapsulates object creation.
- Promotes loose coupling.
- Enhances code maintainability.
Class Diagram:
The participant's classes in this pattern are:
Sequence diagram:
领英推荐
there is nothing perfect so we have Tradeoffs for using the factory method:
- It can lead to a proliferation of factory classes.
- Adds complexity.
what about complex systems and architectures can we integrate it with other patterns?
yes, these Pattern works well with the factory method:
- Abstract Factory (more flexible, but more complicated)
- Singleton(if we needed only one instance of the object)
- Prototype (more flexible, but more complicated)
we will dive deeper into them later but this was an overview of the integration of the factory method with other design patterns.
in general Factory Method which is less complicated and more customizable via subclasses evolves toward Abstract Factory, Prototype, or Builder (more flexible, but more complicated) which we will talk about later.
if you want to delve deeper into understanding and implementing the factory method pattern check out these websites and books:
-Design Patterns Elements of Reusable Object-Oriented Software