StructuralC++verifiedVerified

Adapter Pattern in C++

Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.

How to Implement the Adapter Pattern in C++

1Step 1: Define the target interface clients expect

class JsonLogger {
public:
    virtual ~JsonLogger() = default;
    virtual void logJson(const std::string& json) = 0;
};

2Step 2: The adaptee has an incompatible interface

class LegacyLogger {
public:
    void writeLog(const std::string& severity, const std::string& message) {
        std::cout << "[" << severity << "] " << message << "\n";
    }
};

3Step 3: Adapter wraps the legacy logger to match the target

class LoggerAdapter : public JsonLogger {
    LegacyLogger legacy_;
public:
    void logJson(const std::string& json) override {
        // Extract fields from JSON (simplified)
        legacy_.writeLog("INFO", "Adapted: " + json);
    }
};

int main() {
    std::unique_ptr<JsonLogger> logger = std::make_unique<LoggerAdapter>();
    logger->logJson(R"({"message": "Hello from adapter"})");
}

Adapter Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Adapter Pattern in the Real World

A travel power adapter lets your American laptop plug (client) work in a European wall socket (adaptee) without modifying either. The adapter speaks both “languages”, translating the two-pin plug to the two-round-pin socket, making them interoperable without any changes on either side.