适配器模式 Adapter

适配器模式,调整使之符合另一接口

1类适配器模式,子类继承Adaptee类

#include <IOSTREAM>

using namespace std;

//类适配器



class Target{

public:

    virtual void action() = 0;

};



class Adaptee{

public:

    void Adapteraction(){

        cout<<"hello world"<<endl;

    }

};



class Adapter:public Target,Adaptee{

public:

    void action(){

        this->Adapteraction();

    }

};    



int main(int argc, char* argv[])

{

    Target * p = new Adapter;

    p->action();

    delete p;

    return 0;

}

 

2对象适配器模式,将Adaptee类作为对象存在于Adapter类中,在Adapter类中由Target继承来的接口中调用Adaptee的操作

//对象适配器



class Target{

public:

    virtual void action() = 0;

};



class Adaptee{

public:

    void Adapteraction(){

        cout<<"hello world"<<endl;

    }

};



class Adapter:public Target{

public:

    void action(){

        p->Adapteraction();

    }

    Adapter(){

        p = new Adaptee;

    }

    ~Adapter(){

        delete p;

    }

private:

    Adaptee * p;

};    



int main(int argc, char* argv[])

{

    Target * p = new Adapter;

    p->action();

    delete p;

    return 0;

}

3.缺省适配器模式,

我们将这个中间过渡类称为 “缺省适配类”,缺省适配模式为一个接口提供缺省实现

#include <IOSTREAM>

using namespace std;

//缺省适配器



class Target{

public:

    virtual void action1() = 0;

    virtual void action2() = 0;

    virtual void action3() = 0;

};



class DefaultAdapter:public Target{

public:

    void action1(){

        cout<<"action1"<<endl;

    }

    void action2(){

        cout<<"action2"<<endl;

    }

    void action3(){

        cout<<"action3"<<endl;

    }

};



class Adapter:public DefaultAdapter{

public:

    void action1(){

        cout<<"only want action1"<<endl;

    }

};    



int main(int argc, char* argv[])

{

    Target * p = new Adapter;

    p->action1();

    delete p;

    return 0;

}

 

你可能感兴趣的:(Adapter)