DEV Community

Dawud Ibrahim Ismail
Dawud Ibrahim Ismail

Posted on

Adapter Design Pattern

We all have written code where we needed just few functionality from a class but because of object incompatibility we'll have to create a new class and duplicate this few functionality.

Well, that's where the adapter design pattern comes into play. It's a behavioral design pattern that allows us to use an incompatible class by creating an adapter class.

Say you have a VGA display and your laptop only has port for an HDMI display, then you couldn't connect the display to the laptop unless you connect them via an VGA - HDMI adapter. That's exactly what we to code in adapter pattern, because function is same either with HDMI or VGA display that is to display but the underlying mechanism for achieving it between them is different, thus the adapter bridges the difference in the underlying mechanism, by introducing an adapter class which extends the adaptor class(HDMI) and takes the adapter(VGA) as a parameter.

Because the adapter extends the the adaptor they can be substituted for each other. Now the function needed can be overridden to behave like the adapter or the similar function from the adapter class could be called in the overridden function, creating an illusion of using the incompatible class directly in place of the correct type.

I've modelled this in code using Java. link at: https://github.com/idawud/Adapter-design-pattern

Top comments (0)