Member-only story
The Adapter Pattern in JavaScript
With examples to help you implement it
Have you ever come across code where some function was suffixed with Adapter
? Chances are that you were reading code incorporating compatibility in behavior between two interfaces using the Adapter pattern. This article will go over the Adapter pattern in JavaScript and explain why the pattern is important and why it can be beneficial in modern programming.
The way the Adapter works is that you create a function (which can be a class, but it doesn’t have to be implemented as a class) that adapts its interface’s properties and methods into a new class seamlessly — as if the adapter can still be identified and behave like the original while at the same time being able to work with the new interface.
As web technology in JavaScript is constantly evolving, it’s easy to see this pattern used in open source projects today (e.g. axios-mock-adapter).
How It Looks
There’s no right way to write an Adapter pattern in JavaScript. However, they all share the same goal: to provide compatibility from one interface to another.
For example, if we have a function that takes in a list of objects (which we’ll each call action objects in the upcoming example) and converts them to Action
instances in an array before passing them to another function that calls every one of their execute
methods, then any new introductions to the implementation should follow that similar interface if they want to maintain compatibility.
Let’s take these action objects that share a common actionType
property:
Given these classes, we define: