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 bookAdapter
Structural patternThe Adapter design pattern is used when we encounter incompatible software interfaces, which, even with this inherent incompatibility, have similar features. This pattern is used when we want to work with different interfaces in a homogeneous manner, to that end, we create an intermediate class which functions as an adapter. This adapter class will provide the methods needed for interacting with the incompatible interface.
The components included in this pattern are:
- Client: The actor interacting with the Adapter.
- Target: Interface for homogenizing the manner in which we’re going to work with the incompatible interfaces. This interface is used for creating the Adapters.
- Adapter: It represents the implementation of the Target, which has the responsibility of mediating between the Client and the Adaptee. It hides the communication method with the Adaptee.
- Adaptee: It represents the class with the incompatible interface.
- The Client invokes the Adapter with generic parameters.
- The Adapter converts the generic parameters into specific parameters for the Adaptee.
- The Adapter invokes the Adaptee.
- The Adaptee answers the call.
- The Adapter converts the response of the Adaptee into a generic response for the Client.
- The Adapter attends the Client with a generic response.
Real-world example
By implementing the Adapter design pattern, we are going to create an adapter for interacting homogeneously with two Bank APIs, both of which allow us to approve personal loans. However, even though these APIs work similarly, they have different interfaces, which means that we need to set separate implementations in order to process the loans through each bank. With this pattern, we will create an adapter for hiding the intricacies of each API implementation, by showing only a single interface, compatible with both APIs.