Adapter

Structural pattern

The 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.

Adapter design pattern structure.
Adapter design pattern structure.

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.
Adapter pattern sequence diagram.
Adapter pattern sequence diagram.
  1. The Client invokes the Adapter with generic parameters.
  2. The Adapter converts the generic parameters into specific parameters for the Adaptee.
  3. The Adapter invokes the Adaptee.
  4. The Adaptee answers the call.
  5. The Adapter converts the response of the Adaptee into a generic response for the Client.
  6. 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.

Discover how the Adapter design pattern can help us solving this problem
Discover how the Adapter design pattern can help us solving this problem

About this book

Introduction to design patterns

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
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.