Skip to main content

Adapter Pattern

Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
~ Refactoring Guru

« interface »

ClientInterface

+ method(data)

Client

Adapter

- adaptee: Service

+ method(data)

Service

+ serviceMethod(specialData)

specialData = convertToServiceFormat(data)
return adaptee.serviceMethod(specialData)

Object Adapter UML Class Diagram
Uses object composition to bridge incompatible interfaces between client and service classes. It allows for flexible integration and easy updates to service classes without affecting client code. The adapter implements the interface of one object and wraps the other one. It can be implemented in all popular programming languages.

The Adapter design pattern allows incompatible objects to collaborate by creating a translator class that converts the interface of one object to the format expected by another. This pattern is useful when integrating legacy or third-party code with existing applications. It follows the Single Responsibility and Open/Closed principles, but increases code complexity.

Slides

Adapter Pattern
full screen click here

Step by Step Implementation

In this tutorial, we’ll implement the Adapter Pattern to convert XML data from a service into JSON format for a client that only accepts JSON. We’ll use the object adapter method to wrap the XML service and translate its output to JSON.

Live Editor
function AdapterDemo() {
// XMLService provides data in XML format
class XMLService {
    getDataInXML() {
        return `<data>
        <item>
          <id>1</id>
          <name>Item 1</name>
        </item>
        <item>
          <id>2</id>
          <name>Item 2</name>
        </item>
      </data>`;
    }
}

// JSONClient expects data in JSON format
class JSONClient {
        displayData(jsonData) {
        return JSON.stringify(jsonData, null, 2);
    }
}

const xmlService = new XMLService();
const jsonClient = new JSONClient();
return (
<div>
    <h4>XML Service Data (Unusable by JSONClient):</h4>
    <pre>{xmlService.getDataInXML()}</pre>
</div>
);
}
Result

XML Service Data (Unusable by JSONClient):

<data>
        <item>
          <id>1</id>
          <name>Item 1</name>
        </item>
        <item>
          <id>2</id>
          <name>Item 2</name>
        </item>
      </data>
Report Issue
Provide feedback