首页 > 编程语言 > 详细

【c++设计模式】适配器模式

时间:2019-12-08 11:49:23      阅读:80      评论:0      收藏:0      [点我收藏+]

结构性模式

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

【c++设计模式】适配器模式

原文:https://www.cnblogs.com/corineru/p/12003916.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!