C++设计模式之适配器模式

一、适配器模式

适配器模式(Adapter Pattern)是一种结构型设计模式,用于将一个类的接口转换成另一个类所期望的接口,以便两个类能够协同工作。

适配器模式可以解决现有类接口与所需接口不匹配的问题,使得原本因接口不兼容而无法合作的类可以一起工作。

在C++中,适配器模式通常涉及以下几个角色:

  • 目标接口(Target Interface):定义了客户端代码期望的接口。
  • 适配者(Adaptee):存在的类或组件,其接口与目标接口不匹配。
  • 适配器(Adapter):实现了目标接口,并通过包装适配者的方式将其接口转换为目标接口。

主要应用在以下场景:

  • 新旧接口兼容软件版本升级,部分旧接口还在被使用。需要保留旧的接口,增加新接口,使两者兼容。
  • 第三方接口的适配在系统功能稳定的情况下,有第三方新的接口需求需要对接。
  • 统一多个类相同功能的接口,例如统一不同类型数据库的访问接口。

二、类适配器

以多继承方式实现。

  • Target: 客户端期望接口类
  • Adaptee: 实际需要的功能类
  • Adapter: 将接口类与功能类衔接的适配器类
  • Client: 客户端代码
cpp 复制代码
// 目标接口(新系统的接口)
class Target {
public:
    virtual ~Target() = default;
    virtual void Request() = 0;
};

// 被适配的类(老系统的接口)
class Adaptee {
public:
    void SpecificRequest() {
        // 一些特殊的请求
        cout << "Specific Request of Adaptee!" << endl;
    }
};

// 类适配器
class Adapter : public Target, private Adaptee {
public:
    void Request() override {
        // 将目标接口转化为特殊的请求
        SpecificRequest();
    }
};

int main() {
    Target* target = new Adapter;
    target->Request(); // 输出: Specific Request of Adaptee!

    delete target;
    return 0;
}

三、对象适配器

在适配器类中,包装适配者(Adaptee)接口。

  • Target: 客户端期望接口类
  • Adaptee: 实际需要的功能类
  • Adapter: 将接口类与功能类衔接的适配器类
  • Client: 客户端代码
cpp 复制代码
// 目标接口
class TargetInterface {
public:
    virtual void request() = 0;
};

// 适配者
class Adaptee {
public:
    void specificRequest() {
        // 执行适配者特定的操作
        // ...
    }
};

// 适配器
class Adapter : public TargetInterface {
private:
    Adaptee* adaptee;

public:
    Adapter(Adaptee* adaptee) : adaptee(adaptee) {}

    void request() override {
        // 调用适配者的特定方法
        adaptee->specificRequest();
    }
};

int main() {
    // 创建适配者对象
    Adaptee* adaptee = new Adaptee();

    // 创建适配器对象,将适配者对象传入
    TargetInterface* adapter = new Adapter(adaptee);

    // 调用目标接口方法,实际上会执行适配者的特定方法
    adapter->request();

    delete adapter;
    delete adaptee;

    return 0;
}

四、总结

类适配器模式使用继承来适配接口;
对象适配器模式通过将适配者对象作为适配器类的成员变量来实现适配;

无论是类适配器模式还是对象适配器模式,都可以实现接口适配的效果,选择哪种方式取决于具体的需求和设计考虑。

参考

相关推荐
鱼跃鹰飞29 分钟前
设计模式系列:工厂模式
java·设计模式·系统架构
老蒋每日coding8 小时前
AI Agent 设计模式系列(十九)—— 评估和监控模式
人工智能·设计模式
会员果汁8 小时前
23.设计模式-解释器模式
设计模式·解释器模式
「QT(C++)开发工程师」16 小时前
C++设计模式
开发语言·c++·设计模式
茶本无香16 小时前
设计模式之七—装饰模式(Decorator Pattern)
java·设计模式·装饰器模式
漂洋过海的鱼儿1 天前
设计模式——EIT构型(三)
java·网络·设计模式
老蒋每日coding2 天前
AI Agent 设计模式系列(十八)—— 安全模式
人工智能·安全·设计模式
老蒋每日coding2 天前
AI Agent 设计模式系列(十六)—— 资源感知优化设计模式
人工智能·设计模式·langchain
老蒋每日coding2 天前
AI Agent 设计模式系列(十七)—— 推理设计模式
人工智能·设计模式
冷崖2 天前
桥模式-结构型
c++·设计模式