zoukankan      html  css  js  c++  java
  • 【c++设计模式】适配器模式

    结构型模式

    6)适配器模式

    假设类A想要调用类B中的某个方法,为了避免重写,可以用这个模式。
    有两种方法可以用来实现这种复用。
    第一种是类适配器,利用多重继承的方式实现代码复用。
    第二种是对象适配器,利用组合的方式,在类A中加入类B的指针,然后调用B的方法。

    • 类适配器
    //产品类
    class Electricity{
    public:
        
        virtual void charge(){
            cout<<"this is 220V..."<<endl;
        }
    };
    
    //适配器类
    class Adapter5V{
    public:
        void transfer()
        {
            cout<<"this is 5V..."<<endl;
        }
    };
    
    //采用多重继承的方式,实现代码复用
    class Elecwith5V : public Electricity, public Adapter5V{
    public:
        void charge(){
            transfer(); //直接调用适配器类
        }
    };
    
    int main(){
    
        Electricity* ewithAdapter = new Elecwith5V();
        ewithAdapter->charge();
    }
    
    • 对象适配器类
    //产品类
    class Electricity{
    public:
        
        virtual void charge(){
            cout<<"this is 220V..."<<endl;
        }
    };
    
    //适配器类
    class Adapter5V{
    public:
        void transfer()
        {
            cout<<"this is 5V..."<<endl;
        }
    };
    
    //采用组合的方式,实现代码复用
    class Elecwith5V: public Electricity{
    public:
        Elecwith5V():p_adapter(NULL){
            p_adapter = new Adapter5V();
        }
        void charge(){
            p_adapter->transfer(); 
        }
    private:
        Adapter5V* p_adapter;
    };
    
    int main(){
    
        Electricity* ewithAdapter = new Elecwith5V();
        ewithAdapter->charge();
    }
    
  • 相关阅读:
    DDT驱动selenium自动化测试
    python 对Excel表格的读取
    python 对Excel表格的写入
    selenium对百度进行登录注销
    selenium的八大定位元素的方式
    selenium打开Chrome浏览器并最大化
    行列式计算的归纳
    C标准库函数getchar()
    测试必备-抓包工具的使用
    uiautomator2使用教程
  • 原文地址:https://www.cnblogs.com/corineru/p/12003916.html
Copyright © 2011-2022 走看看