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

四、总结

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

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

参考

相关推荐
da_vinci_x21 小时前
武器设计实战:一把大剑裂变 5 种属性?Structure Ref 的“换肤”魔法
游戏·3d·设计模式·ai作画·aigc·设计师·游戏美术
刀法孜然1 天前
23种设计模式 3 行为型模式 之3.7 command 命令模式
设计模式·命令模式
一条闲鱼_mytube1 天前
智能体设计模式(二)反思-工具使用-规划
网络·人工智能·设计模式
老蒋每日coding1 天前
AI智能体设计模式系列(七)—— 多 Agent 协作模式
设计模式
小码过河.1 天前
设计模式——代理模式
设计模式·代理模式
Engineer邓祥浩1 天前
设计模式学习(14) 23-12 代理模式
学习·设计模式·代理模式
小码过河.1 天前
设计模式——单例模式
单例模式·设计模式
dxnb221 天前
Datawhale26年1月组队学习:Agentic AI+Task2反思设计模式
学习·设计模式
老蒋每日coding1 天前
AI智能体设计模式系列(八)—— 记忆管理模式
人工智能·设计模式·golang
Mr YiRan1 天前
重学设计模式之拦截器和责任链
设计模式