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 bookAbstract Factory
Creational patternThe goal of the Abstract Factory design pattern is to form a group of classes with shared functionalities, better known as families, created by a Factory. This pattern is especially useful when we need to implement certain class families to solve a problem, however, we may need to add parallel implementations of the same classes to solve the same problem with a different approach.
The structure of Abstract Factory may look quite convoluted since it has many components which seem to intertwine with each other. To better explain how this pattern works, let's review its components one by one:
- Client: It represents the actor or event which triggers the execution of the pattern.
- AbstractProduct (A, B): Interfaces for defining the object structure of each family.
- ConcreteProduct (A, B): Classes that inherit their properties from AbstractProduct for implementing entire families of concrete objects.
- ConcreteFactory: They represent the concrete factories that will create instances of all the classes of the family. This class must have a method for creating each and every one of the classes of the family.
- AbstractFactory: They define the structure of the families. They must provide a method for each and every one of the classes of the family.
- The client sends a request to AbstractFactory al ConcreteFactory1 .
- The AbstractFactory creates an instance of ConcreteFactory1 and returns it.
- The client sends a request to ConcreteFactory1 for the creation of ProductA .
- The ConcreteFactory1 creates an instance of ProductA1 which is a member of family1, and returns it.
- Now the client sends a request to AbstractFactory al ConcreteFactory2 .
- The AbstractFactory creates an instance of ConcreteFactory2 .
- The client sends a request to ConcreteFactory2 for the creation of ProductA .
- The ConcreteFactory2 creates an instance of ProductA2 which is a member of Family2, and returns it.
Real-world example
By implementing theAbstract Factory design pattern, we are going to develop an application for communicating with a Backend system via Web Services and REST, in order to give the client the option to use any of these methods by configuration.