Adapter Pattern
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
~ Refactoring Guru
- Object Adapter
- Class Adapter
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
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> |