06-适配器模式(Adapter)

意图

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

结构

类适配器使用多重继承对一个接口与另一个接口进行匹配

06-适配器模式(Adapter)

类适配器示意图

对象匹配器依赖于对象组合

06-适配器模式(Adapter)

对象适配器示意图

代码示例

类适配器代码示例:

#include <iostream>

// 接口
class Target {
public:
    Target() {}
    virtual ~Target() {}
    virtual void Request() = 0;
};
// 被适配类
class Adaptee {
public:
    Adaptee() {}
    virtual ~Adaptee() {}
    void SpecificRequest() {
        std::cout << "Do something!" << std::endl;
    }
};
// 适配器
class Adapter : public Target, public Adaptee {
public:
    Adapter() : Target(), Adaptee() {}
    virtual ~Adapter() {}
    void Request() override {
        SpecificRequest();
    }
};

// use it!
int main(int argc, char* argv[]) {
    Target* t = new  Adapter();
    t->Request();
    return 0;
}

对象适配器代码示例:

#include <iostream>

// 接口
class Target {
public:
    Target() {}
    virtual ~Target() {}
    virtual void Request() = 0;
};
// 被适配类
class Adaptee {
public:
    Adaptee() {}
    virtual ~Adaptee() {}
    void SpecificRequest() {
        std::cout << "Do something!" << std::endl;
    }
};
// 适配器
class Adapter : public Target {
public:
    Adapter() : Target() {}
    virtual ~Adapter() {}
    void Request() override {
        _adaptee.SpecificRequest();
    }
private:
    Adaptee _adaptee;
};

// use it!
int main(int argc, char* argv[]) {
    Target* t = new  Adapter();
    t->Request();
    return 0;
}

适用性

  1. 你想使用一个已经存在的类,而它的接口不符合你的需求;
  1. 你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作;
  1. 你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。