Adapter design pattern

What is adapter design pattern?

Two incompatible interfaces communicate with an adapter. An Adapter pattern works as a bridge between two incompatible interfaces.

In short, the Adapter pattern links two incompatible interfaces.

Advantages of adapter design pattern:

  • In adapters, polymorphism is used between different implementations
  • The adapter design pattern allows previously incompatible objects to interact
  • The adapter design pattern allows the reusability of existing functionality
  • It promotes loose coupling and the single responsibility principle
  • It helps in implementing a third-party library

Disadvantages of adapter design pattern:

  • The overall complexity of the code increases because of new interfaces and classes.
  • In some cases, it is easier to change the service class so that it matches the rest of the code.

Example of adapter design pattern:

// Target.ts
export interface Target {
    convert(xml: string): JSONData;
}

export type JSONData = {};



// Adapter.ts
import {Target, JSONData} from "./Target";
import {Adaptee} from "./Adaptee";


export class XmlToJSONAdapter implements Target {
    private xmlData: string;
    constructor(xml: string) {
        this.xmlData = xml;
    }
    public convert(): JSONData {
        console.log("XmlToJSONAdapter's `convert` method is being called");
        const adaptee = new Adaptee();
        return adaptee.convertToJSON(this.xmlData);
    }
}




// Adaptee.ts
import {JSONData} from "./Target";

export class Adaptee {
    public convertToJSON(xml: string): JSONData {
        console.log("`convertToJSON` of Adaptee is being called");
        return {};
    }
}



// Client.ts
import {XmlToJSONAdapter} from "./adapter";

const xmlData = 'xml data goes here';
const adapter = new XmlToJSONAdapter(xmlData);
const jsonData = adapter.convert();

// Let say the tax calculation only works with json data. The system provides xml data. We can use the Adapter design patter to convert the data type to calculate the tax. 

// const tax = calculateTax(jsonData);