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;
}

四、总结

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

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

参考

相关推荐
yangpipi-3 小时前
2. 设计模式之结构型模式
设计模式
进击的小头8 小时前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
致Great8 小时前
智能体的设计模式探讨
设计模式
BD_Marathon9 小时前
设计模式——单一职责原则
设计模式·单一职责原则
stevenzqzq10 小时前
Slot API 设计模式
设计模式·compose
reddingtons10 小时前
Cascadeur:动态总是“飘”?“物理外挂流” 3分钟直出重力感 2D 立绘
游戏·设计模式·aigc·设计师·游戏策划·游戏美术·cascadeur
Wyy_9527*10 小时前
行为型设计模式——策略模式
设计模式·策略模式
kogorou0105-bit11 小时前
前端设计模式:发布订阅与依赖倒置的解耦之道
前端·设计模式·面试·状态模式
BD_Marathon11 小时前
设计模式——接口隔离原则
java·设计模式·接口隔离原则
小码过河.1 天前
设计模式——适配器模式
设计模式·适配器模式