【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();
}
原文地址:https://www.cnblogs.com/corineru/p/12003916.html