Adapter Pattern in JavaScript with example

ZainDev
1 min readAug 25, 2023

--

const javascriptFunction = function(name) {
return "Hello, " + name;
};

const Adapter = function(javascriptFunction) {
this.javascriptFunction = javascriptFunction;

this.getGreeting = function(name) {
return this.javascriptFunction(name);
};
};

const adapter = new Adapter(javascriptFunction);

console.log(adapter.getGreeting("World"));

In this example, the javascriptFunction function is the adaptee. It has an interface that expects a name as input and returns a greeting. The Adapter class is the adapter. It adapts the javascriptFunction function to the getGreeting() method of the NewAPI interface. The Adapter class does this by calling the javascriptFunction function with the name as input and returning the result.

The adapter pattern can be used in a variety of ways in JavaScript. It is a versatile pattern that can be used to solve a variety of problems.

Here are some other examples of the adapter pattern in JavaScript:

  • Adapting a legacy API to a new interface
  • Adapting a third-party library to your own code
  • Adapting a data format to a different data format

The adapter pattern is a powerful tool that can be used to improve the flexibility and maintainability of your JavaScript code.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

ZainDev
ZainDev

Written by ZainDev

Software Engineer - Senior Full Stack Developer (Tech and Project Lead) ✓Angular ✓React ✓Next ✓Node ✓WebSocket ✓JavaScript ✓TypeScript

No responses yet

Write a response