适配器模式C++

适配器模式,是将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式结构图

适配器模式C++_第1张图片
image

适配器模式基本代码

#include 
using namespace std;

class Target {  // Target,客户期望的接口,可以使具体或抽象的类,也可以是接口
public:
    virtual void Request() = 0;
    virtual ~Target(){};
};

class Adaptee { // 需适配的类
public:
    void SpecificRequest() { cout << "Adaptee" << endl; }
};

class Adapter : public Target { // 通过内部包装一个Adaptee对象,把源接口转换为目标接口:
private:
    Adaptee* adaptee;
public:
    Adapter() { adaptee = new Adaptee(); }
    void Request() { adaptee->SpecificRequest(); }  // 调用Request()方法会转换成调用adaptee.SpecificRequest()
    ~Adapter() { delete adaptee; }
};

int main() {
    Target* target = new Adapter();
    target->Request();

    delete target;
    return 0;
}

应用场景

系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与服用环境要求不一致的情况。

你可能感兴趣的:(适配器模式C++)