Design Pattern in simplicity: Adapter Pattern

Kenneth Cheung
< />
Published in
2 min readMar 10, 2018

--

In case you don’t know what this series is about. Here is the link to the first Article in the series. The first section of that article is the motivation and introduction of the series. I hope it helps you to understand more about the objective of this series.

Adapter Pattern

Adapter Pattern is an easy-to-understand pattern in the GoF Design Patterns. As its name, Adapter Pattern transfer an incompatible interface to a compatible interface.

Image From Best Buy

For instance, you have a legacy module. It has provide functionalities you need, but its interface does not fit the new application you are currently developing. One thing you can do is provide the legacy module a wrapper to transfer its interface to the one can be used in the new application.

Very simple but powerful concept, right?

Example

We have a overlap checking function to help us calculate whether two rectangles overlap to each other or note. Let’s what the function looks like:

const checkOverlap = (
topLeft1, w1, h1,
topLeft2, w2, h2
) => {
// ...skip the steps
return isOverlap; // boolean
}

It takes the topLeft, the width wand the height h to represent a rectangle. We are all happy with it for now.

At some point in the future, the application changes its representation for rectangle from the one we mention above to topLeft and bottomRight for some reasons, but we still need the wonderful checkOverlap function. One way to do that is provide a wrapper to convert the new representation of input to the original one, like this:

const checkOverlapV2 = (
topLeft1, bottomRight1,
topLeft2, bottomRight2
) => {
//... calculate w1, h1, w2, h2 from the arguments
return checkOverlap(
topLeft1, w1, h1,
topLeft2, w2, h2
);
}

Now, we can use the legacy function without rewriting it. Cheers!

Conclusion

Adapter Pattern provides an elegant way to reuse code incompatible with the existing environment. It is very helpful when you have a lot of complicated legacy modules which you want to reuse. I hope this article helps you have basic understanding of adapter pattern. If you want to learn more about this, you can checkout the links in the references, thanks!

References

--

--