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

适配器模式C++实现

时间:2020-05-16 18:53:42      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:stream   spec   main   vat   lan   info   public   适配器模式   mamicode   

类适配器

技术图片

#include <iostream>
using namespace std;

// Target
class Target {
public:
    virtual void Request() {
        cout << "Target::Request" << endl;
    }
};

// Adaptee
class Adaptee {
public:
    void SpecificRequest() {
        cout << "Adaptee::SpecificRequest" << endl;
    }
};

// Adapter
class Adapter : public Target,Adaptee {
public:
    void Request() {
        Adaptee::SpecificRequest();
    }
};

// Client
int main() {
    Target * pTarget = new Adapter();
    pTarget->Request();

    if (pTarget) delete pTarget;
    return 0;
}

对象适配器

技术图片

#include <iostream>
using namespace std;

// Target
class Target {
public:
    Target(){}
    virtual ~Target(){}
    virtual void Request() {
        cout << "Target::Request" << endl;
    }
};

// Adaptee
class Adaptee {
public:
    void SpecificRequest() {
        cout << "Adaptee::SpecificRequest" << endl;
    }
};

// Adapter
class Adapter : public Target,Adaptee {
public:
    Adapter() : m_Adaptee(new Adaptee) {}

    ~Adapter() {
        if (m_Adaptee != NULL) {
            delete m_Adaptee;
        }
    }

    void Request() {
        m_Adaptee->SpecificRequest();
    }
private:
    Adaptee *m_Adaptee;
};

// Client
int main() {
    Target * pTarget = new Adapter();
    pTarget->Request();

    if (pTarget) delete pTarget;
    return 0;
}

适配器模式C++实现

标签:stream   spec   main   vat   lan   info   public   适配器模式   mamicode   

原文地址:https://www.cnblogs.com/wstong/p/12901003.html

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