Adapter Design Pattern
The Adapter Design Pattern is one of the Structural Design Patterns. It allows classes with incompatible interfaces to work together by introducing a wrapper class called an Adapter.
Sometimes an application needs to use an existing class or a third-party library whose interface does not match what the application expects. Rather than modifying either the client code or the existing class, an adapter translates one interface into another.
A real-world example is a travel plug adapter. A device with a US plug cannot connect directly to a European socket, but an adapter sits between them and allows both to work together without changing either the plug or the socket.
This document demonstrates two practical examples of implementing the Adapter Design Pattern in C++.
Example 1: Legacy Inventory System
This example demonstrates connecting a legacy inventory system with a modern analytics application.
Program
Explanation
The modern application expects prices as a double, but the legacy inventory system returns prices as a std::string.
The PriceAdapter wraps the legacy system and converts the returned string into a numeric value using std::stod().
The client communicates only with the target interface and remains completely unaware of the legacy implementation.
Example 2: XML Sensor to JSON Dashboard
This example demonstrates integrating a third-party XML sensor into an application that expects climate data in JSON format.
Program
Explanation
The application dashboard understands only JSON-formatted climate data.
However, the vendor sensor provides XML output. The XmlSensorAdapter receives the XML data and converts it into the JSON format expected by the client.
This allows the dashboard to work with the third-party sensor without modifying either the dashboard or the sensor library.
Characteristics of the Adapter Design Pattern
| Property | Description |
|---|---|
| Pattern Type | Structural Design Pattern |
| Core Principle | Convert one interface into another interface expected by the client. |
| Main Components | Target Interface, Adaptee, Adapter, and Client. |
| Primary Benefit | Enables existing or third-party classes to work together without modifying their source code. |
| Common Applications | Legacy system integration, third-party libraries, hardware drivers, payment gateways, and data format conversion. |
Conclusion
The Adapter Design Pattern enables incompatible classes to collaborate by introducing a translation layer between them. It allows applications to reuse existing components without changing their implementation, making integration with legacy systems and third-party libraries significantly easier. As demonstrated in the Legacy Inventory System and XML Sensor examples, the Adapter pattern improves flexibility while keeping client code simple and independent of implementation details.