Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
Factory MethodCreational pattern
Factory Method allows us to create objects from an specific subtype through a Factory class. This is especially useful when we don't know which subtype we are going to use at design-time, or when do we want to delegate object creation logic to a Factory class. Using this pattern we can dynamically create instances by writing implementation settings on a text file, a XML file, on properties, or using any other strategy.
These are the components included in the pattern:
- IProduct: It represents, in an abstract manner, the object we want to create. This interface is used for defining the structure of the object.
- ConcreteProduct: It represents the concrete implementation of the IProduct interface, which is created by the ConcreteFactory.
- AbstractFactory: This component is optional, however, it would be recommendable to create an AbstractFactory for defining the default behavior of the ConcreteFactory.
- Concrete Factory: It is used for creating the ConcreteProduct, this class inherits its behavior from the AbstractFactory.
- The client requests ConcreteFactory for the creation of ProductA .
- ConcreteFactory finds the concrete implementation of ProductA and creates a new instance.
- ConcreteFactory returns a new ConcreteProductA .
- The client requests ConcreteFactory for the creation of ProductB.
- ConcreteFactory finds the concrete implementation of ProductB and creates a new instance.
- ConcreteFactory returns a new ConcreteProductB .
By implementing the Factory Method design pattern, we are going to create an application capable of connecting with one or more databases, and switching from one to other only by changing settings and without having to write additional lines of code.