适配器模式C++实现

类适配器

#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;
}
posted @ 2020-05-16 17:45  麻辣猪仔  阅读(222)  评论(0编辑  收藏  举报