码迷,mamicode.com
首页 > 其他好文 > 详细

适配器模式 Adapter

时间:2015-07-07 21:13:14      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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

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

标签:

原文地址:http://www.cnblogs.com/xiumukediao/p/4628429.html

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