Factory Method | Cheat Sheet
Creational Pattern — Design Patterns Series
The Factory Method is one of the most known Design Patterns and often used when creating things with same behavior, but with different specifications. This is made possible by delegation of the instantiation process to the specified subclass. This includes specialization options for subclasses, as this pattern provides an extended version of the object compared to the direct creation of the object.
If you want to use a Creational Pattern, but are unsure which one, you can start by implementing the Factory Method. Due to its high flexibility, the Factory Method is the easiest to integrate into the system and later you can switch to other Creational Patterns easily.
Real-life examples
- Things with same behaviour, but different specifications: Animal Factory, Logistics Factory (delivery method or transport vehicle)
Meaning
- Abstract interface for object creation, where the determination of the class to be instantiated is left to the subclass
- Delegation of instantiation to a subclass
Applicability
- Classes to be created cannot be determined in advance, therefore an abstract interface is provided which can be reached via a function
- A class expects from its subclasses a specification of the products to be created
Assets and Drawbacks
- Specialization options for subclasses, as this pattern provides an extended version of the object compared to the direct creation of the object
Best Practises
- If you want to use a Creational Pattern, but are unsure which one, you can start by implementing the Factory Method
- Later you can switch to other Creational Patterns
- Due to its high flexibility the Factory Method is the easiest to integrate into the system
Example
First of all, you need to define a product.
For this example I chose types of food.
After that, you can define the abstract Creator and its subclasses to create some pizzas and wraps.
The client could consume the Factory Method as follows.
Conclusion
Design Patterns are an important resource and base knowledge for every developer — they are very helpful for solving programmatic problems, help with consistent communication with other developers about system design, and are a significant introduction into object composition (besides inheritance) and dependency inversion.
Creational Patterns are indispensable when abstracting the instantiation process of objects. Of high importance are encapsulation of concrete classes and hiding the creational process.