0
0
JavascriptConceptBeginner · 3 min read

Adapter Pattern in JavaScript: What It Is and How It Works

The adapter pattern in JavaScript is a design pattern that allows incompatible interfaces to work together by wrapping one interface with another. It acts like a translator between two objects so they can communicate smoothly without changing their original code.
⚙️

How It Works

Imagine you have a phone charger that fits only a certain type of socket, but you want to use it in a different socket type. The adapter pattern works like a plug adapter that changes the charger’s plug to fit the socket. In JavaScript, it wraps an object with a new interface so that the original object can be used where a different interface is expected.

This means you don’t have to change the original object’s code. Instead, you create an adapter that translates calls from the client to the original object’s methods. This helps when integrating third-party code or legacy systems that don’t match your current code’s interface.

💻

Example

This example shows a simple adapter that allows a OldCalculator with a different method name to be used where a NewCalculator interface is expected.

javascript
class OldCalculator {
  operations(t1, t2, operation) {
    switch (operation) {
      case 'add':
        return t1 + t2;
      case 'sub':
        return t1 - t2;
      default:
        return NaN;
    }
  }
}

class CalculatorAdapter {
  constructor() {
    this.oldCalc = new OldCalculator();
  }

  add(t1, t2) {
    return this.oldCalc.operations(t1, t2, 'add');
  }

  subtract(t1, t2) {
    return this.oldCalc.operations(t1, t2, 'sub');
  }
}

const calc = new CalculatorAdapter();
console.log(calc.add(10, 5));
console.log(calc.subtract(10, 5));
Output
15 5
🎯

When to Use

Use the adapter pattern when you want to use existing code that has a different interface than what your current code expects. It is helpful when integrating third-party libraries, legacy code, or APIs that don’t match your design.

For example, if you have a new system that expects certain method names but you want to reuse an old module without changing it, an adapter can translate between the two. This keeps your code clean and avoids rewriting working code.

Key Points

  • The adapter pattern wraps an object to provide a different interface.
  • It allows incompatible interfaces to work together without changing original code.
  • It acts like a translator or bridge between two systems.
  • Commonly used for integrating legacy or third-party code.

Key Takeaways

The adapter pattern helps incompatible interfaces work together by wrapping one with another.
It avoids changing existing code by translating method calls through an adapter.
Use it to integrate legacy systems or third-party libraries smoothly.
It acts like a plug adapter that fits different sockets without modifying the plug.
Adapters keep your code flexible and maintainable when dealing with different interfaces.