zoukankan      html  css  js  c++  java
  • 适配器模式 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;
    }
  • 相关阅读:
    一、操作m'y's'ql
    十三、并发
    十二、异步_实践
    一、数据
    【2019-08-13】琐碎事才是突破
    【2019-08-12】迟到好过没到
    【2019-08-11】别人约我宵夜,我却约人早茶
    【2019-08-10】习惯跟时间有关
    【2019-08-09】一日之计在于晨
    【2019-08-08】少即是多,慢即是快
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4628429.html
Copyright © 2011-2022 走看看