Adapter Pattern

Posted by Dustin Boston in .

The Adapter Pattern is a structural design pattern that helps incompatible interfaces work together by using an adapter class. This article explains how it works and its benefits in software development.


The Adapter Pattern is a structural design pattern that allows incompatible interfaces to work together by creating a wrapper or adapter class. This adapter translates the interface of one class into an interface that a client expects, enabling seamless integration without modifying existing code.

Source Code Listing

code.ts

type Target = {
  request(): void;
};

class ConcreteTarget implements Target {
  request(): void {
    console.log("Target request"); // More descriptive output
  }
}

class Adaptee {
  specificRequest(): void {
    console.log("Specific request");
  }
}

class Adapter implements Target {
  constructor(private readonly adaptee: Adaptee) {}

  request(): void {
    this.adaptee.specificRequest();
  }
}

const client = {
  run(): void {
    const adaptee = new Adaptee();
    const adapter = new Adapter(adaptee);
    adapter.request();

    const target = new ConcreteTarget(); // Demonstrate using the original Target
    target.request();
  },
};

client.run();