Adapter (Design Pattern)

This structural pattern translates one class interface into another.



This is a class adapter, but there also exists an object adapter.


#include <memory>
#include <iostream>
 
// Interface
class IUsbCSocket {
public:
    virtual void justConnect() = 0;
};
 
// Legacy class
class MicroUsbSocket {
public:
    void lookThenConnect() {
        std::cout << "Look then connect Micro-USB." << std::endl;
    }
};
 
// Adapter class
class UsbC2MicroUsbSocketAdapter :
    public IUsbCSocket, private MicroUsbSocket {
public:
    void justConnect() override {
        std::cout << "Just connect USB-C." << std::endl;
        lookThenConnect();
    }
};
 
int main() {
    std::unique_ptr<IUsbCSocket> socket(new UsbC2MicroUsbSocketAdapter());
    socket->justConnect();
    // ...
    return 0;
}