码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-12-08 12:28:52      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:结构   tran   cout   模式   复用   end   this   private   nsf   

结构性模式

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++设计模式】适配器模式

标签:结构   tran   cout   模式   复用   end   this   private   nsf   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!