#include <iostream> #include <memory> #include <string> // 目标接口:新的日志接口 class Logger { public: virtual ~Logger() {} virtual void logMessage(const std::string& message) const = 0; }; // 现有接口:旧的日志系统 class OldLogger { public: void writeLog(const std::string& msg) const { std::cout << "Old Logger: " << msg << std::endl; } }; // 对象适配器类:将旧的日志系统适配为新的日志接口 class LoggerAdapter : public Logger { private: std::shared_ptr<OldLogger> oldLogger; public: LoggerAdapter(std::shared_ptr<OldLogger> oldLogger) : oldLogger(oldLogger) {} void logMessage(const std::string& message) const override { oldLogger->writeLog(message); } }; // 类适配器类:将旧的日志系统适配为新的日志接口 class ClassLoggerAdapter : public Logger, private OldLogger { public: void logMessage(const std::string& message) const override { writeLog(message); } }; int main() { // 使用旧的日志系统 std::shared_ptr<OldLogger> oldLogger = std::make_shared<OldLogger>(); oldLogger->writeLog("Logging with the old logger"); // 使用对象适配器将旧的日志系统适配为新的日志接口 std::shared_ptr<Logger> logger = std::make_shared<LoggerAdapter>(oldLogger); logger->logMessage("Logging with the object adapter"); // 使用类适配器将旧的日志系统适配为新的日志接口 std::shared_ptr<Logger> classLogger = std::make_shared<ClassLoggerAdapter>(); classLogger->logMessage("Logging with the class adapter"); return 0; }