Adapter Design Pattern
Prateek Mishra
Software Engineer at Google | ex. Microsoft, Walmart | Gold Medalist, IIIT Allahabad | XAT'24: 99.8
An adapter is, like we all know, a bridge that facilitates communication between two incompatible interfaces. Adapter pattern is no different.
Consider you have a phone (Client) that only has a typeC port and you wish to use your favorite wired headphones (External Service) with it. But you just can't plug in your old headphones straightaway. You need to use a TypeC to headphone jack adapter (Adapter). Similarly, at times in software engineering, we encounter classes that can't communicate. But we need them to communicate as per our logic. A common example would be an application that uses protobuf for internal communication but also uses an external API that returns data only in the json format. Here we need a json-to-protobuf adapter.
Adapter pattern offers us certain advantages in comparison to hardcoding this conversion logic in the application classes:
Here is what the implementation looks like :
In the implementation we make an adapter class and make it extend the TypeCDevice (Service). So Adapter is now a TypeCDevice. Then we put a Headphones (Client) variable in our class. This way we communicate the instructions to the headphones. Now we simply give our new adapter to the typeCPort. And Voila! Our favorite wired headphones now work with our brand new phone.
Have you used this pattern in your work before? Comment down below. Hope you learnt something new today. I write such posts regularly. Follow Prateek Mishra and learn something new every week.
To write this article I took help from the following sources: