Adapter Design Pattern

Adapter Design Pattern

Design Patterns Serie

Intent

It allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. So, it lets classes work together that couldn't otherwise because of incompatible interfaces.

Problem

I think the following image is self explanatory enough :

image.png

So, what should you do if you have a house with an incompatible outlet to a device? Should you move to another house to charge the second device? Absolutely not!

Solution

The solution is to use an electric adapter!
So, the Adapter design pattern works in programming like adapters work in real life which is to allow objects with incompatible interfaces to collaborate.

Pros and Cons

Pros

  • We can separate the interface code from the business logic of the program. So the "Single Responsibility Principle" is achieved here. A change in either the client interface only means a change to the adapter.
  • We can bring new types of adapters into the program without causing any problems in the existing client code (as long as they work with the adapters through the client interface) So we can achieve the "Open/Closed Principle". So, we can use code from third parties relatively seamlessly.

Cons

  • In some cases, It’s easier to manually refactor the client interface than to use the adapter design pattern.
  • The complexity of the code increases as long as you bring new classes, and interfaces.

Thank you, and goodbye.