StructuralTypeScriptverifiedVerified

Adapter Pattern in TypeScript

Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.

How to Implement the Adapter Pattern in TypeScript

1Step 1: Define the target interface and the incompatible adaptee

interface Target {
  request(): string;
}

class Adaptee {
  specificRequest(): string {
    return "Adaptee: specific behaviour";
  }
}

2Step 2: Implement the adapter that bridges both interfaces

class Adapter implements Target {
  private adaptee: Adaptee;

  constructor(adaptee: Adaptee) {
    this.adaptee = adaptee;
  }

  request(): string {
    const result = this.adaptee.specificRequest().split("").reverse().join("");
    return `Adapter: (translated) ${result}`;
  }
}

3Step 3: Use the adapter transparently through the target interface

function clientCode(target: Target): void {
  console.log(target.request());
}

const adaptee = new Adaptee();
console.log("Adaptee: " + adaptee.specificRequest());

const adapter = new Adapter(adaptee);
clientCode(adapter);
// Output:
// Adaptee: Adaptee: specific behaviour
// Adapter: (translated) ruoivaheb cificeps :eetpadA

Adapter Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Adapter Pattern in the Real World

A travel power adapter lets your American laptop plug (client) work in a European wall socket (adaptee) without modifying either. The adapter speaks both “languages”, translating the two-pin plug to the two-round-pin socket, making them interoperable without any changes on either side.