设计模式-适配器模式

适配器模式

适配器模式应用场景

​ Rock老师买了一个日本进口机器人,机器人充电要求电压(110V)与国内插头标准电压(220V)不兼容,咋办?

​ 解决方案:

​ 设置一个适配器将插头输出的220V转变为110V

以上的解决方案就是通过一个适配器来解决接口不一致的问题,使原本由于接口不兼容而不能一起工作的那些类可以在一起工作

适配器模式的实现要点

  • 定义一个包装类,用于包装不兼容接口的对象

  • 包装类 = 适配器Adapter

  • 类的适配器模式是把适配器的类的API转换为成为目标类的API

设计类图

对象适配器模式的结构图如下图所示

cpp 复制代码
#include <iostream>
#include <string>

//类模式
namespace adapter_class{
    //目标接口
    class Target{
    public:
        virtual void request() = 0;
    };

    //适配者类
    class Adaptee{
    public:
        void specificRequest(){
            std::cout<< "适配者中的业务代码被调用~"<<std::endl;

        }
    };
    //类适配器类
    class ClassAdapter: public Target,private Adaptee{
    public:
        ClassAdapter(){};
        ~ClassAdapter(){}; 
        virtual void request(){
            std::cout<<"Adapter::Request()"<<std::endl;
            this->specificRequest();
            std::cout<<"--------------------"<<std::cout;
        }
    };

};

//对象模式
namespace adapter_obj{
    class Target{
        public:
            virtual void request() = 0;
    };
    class Adaptee{
    public:
        void specificRequest(){
            std::cout<< "适配者中的业务代码被调用~"<<std::endl;

        }
    };
    class Adapter1:public Target{
        public:
            Adapter1(Adaptee* adaptee):_adaptee(adaptee){};
            ~Adapter1() {};
            virtual void request(){_adaptee->specificRequest();}

        private:
            Adaptee* _adaptee;
    };
};

int main(void){
    std::cout<<"类适配器模式测试:"<<std::endl;
    adapter_class::Target *target = new adapter_class::ClassAdapter();
    target->request();

    std::cout<<"对象适配器模式测试:"<<std::endl;
    adapter_obj::Adaptee *ade       =     new adapter_obj::Adaptee();
    adapter_obj::Target* pTarget    =     new adapter_obj::Adapter1(ade);
    

}

适配器模式的优点

相关推荐
Elaine33612 小时前
【Agent 设计模式全景图:从 ReAct 到工业级多智能体架构】
设计模式·llm·软件架构·ai agent
han_13 小时前
JavaScript设计模式(六):职责链模式实现与应用
前端·javascript·设计模式
无籽西瓜a14 小时前
【西瓜带你学设计模式 | 第三期-工厂方法模式】工厂方法模式——定义、实现方式、优缺点与适用场景以及注意事项
java·后端·设计模式·工厂方法模式
无籽西瓜a15 小时前
【西瓜带你学设计模式 | 第四期 - 抽象工厂模式】抽象工厂模式 —— 定义、核心结构、实战示例、优缺点与适用场景及模式区别
java·后端·设计模式·软件工程·抽象工厂模式
￰meteor16 小时前
23种设计模式 -【抽象工厂】
后端·设计模式
程序员小寒17 小时前
JavaScript设计模式(五):装饰者模式实现与应用
前端·javascript·设计模式
workflower1 天前
设计模式的分类
设计模式·集成测试·软件工程·软件构建·软件需求·结对编程
han_1 天前
JavaScript设计模式(五):装饰者模式实现与应用
前端·javascript·设计模式
wwdoffice01102 天前
SGP夹层玻璃的应用与SGP胶片特性
设计模式
途经六月的绽放2 天前
常见设计模式及其应用示例
java·设计模式