Contact Me

Adapter

 It is a structural design pattern that allows you to convert the interface of a class into another interface that clients expect. This can be useful when you want to reuse an existing class, but its interface does not match the one that you need.


Here is an example of the adapter pattern in JavaScript:


// The target interface

class Target {

request() {

  console.log('Target: Handling request.');

}

}

// The adaptee class

class Adaptee {

specificRequest() {

  console.log('Adaptee: Handling specific request.');

}

}

// The adapter class

class Adapter extends Target {

constructor(adaptee) {

  super();

  this.adaptee = adaptee;

}

request() {

  console.log('Adapter: Delegating request to Adaptee.');

  this.adaptee.specificRequest();

}

}

// Client code

const target = new Target();

target.request();

const adaptee = new Adaptee();

const adapter = new Adapter(adaptee);

adapter.request();


In this example, the Target interface defines a request() method that the client expects. The Adaptee class has a different method, specificRequest(), that needs to be adapted to the request() method expected by the client.

To do this, we create an Adapter class that extends the Target class and holds a reference to an instance of the Adaptee class. The Adapter class implements the request() method by delegating to the specificRequest() method of the Adaptee instance.

The client code can then work with the Target interface, calling the request() method on a Target instance. If the client has a Target instance, it can use it directly. If the client has an instance of the Adaptee class, it can use the Adapter to wrap it and call the request() method on the adapter.