Sobes.tech
Middle

How is an adapter related to the 'Adapter' pattern?

sobes.tech AI

Answer from AI

An adapter in general is a "connector" or "converter" that allows incompatible entities to interact.

The "Adapter" pattern in programming implements this very idea. It allows classes with incompatible interfaces to work together by wrapping one class in another. The adapter converts the interface of one class into another interface expected by the client.

For example:

// Incompatible interface
class OldSystem {
  oldRequest() {
    console.log("Request in the old system");
  }
}

// New interface expected by the client
class NewSystemTarget {
  request() {
    console.log("Request in the new system");
  }
}

// Adapter pattern
class OldSystemAdapter extends NewSystemTarget {
  constructor(oldSystem) {
    super();
    this.oldSystem = oldSystem;
  }

  request() {
    // Adapter converts the call of the new interface into a call to the old one
    this.oldSystem.oldRequest();
  }
}

// Client works with the new (target) interface
const oldSystem = new OldSystem();
const adapter = new OldSystemAdapter(oldSystem);

// Client calls the request method without knowing the internal workings of OldSystem
adapter.request(); // Outputs "Request in the old system"