C++二十三种设计模式之适配器模式
C++二十三种设计模式之适配器模式
- 一、组成
- 二、特点
- 三、目的
- 四、缺点
- 五、示例代码
一、组成
抽象适配器类:声明转换器接口。
具体适配器类:拥有适配者类的持有,实现转换器接口。
适配者类:被适配的类。
二、特点
1、在具体适配器内通过转换器接口调用适配者类的函数来实现适配。
三、目的
解决对象之间接口不兼容的问题。
四、缺点
1、性能开销问题,如果需要频繁调用适配者对象接口,适配器接口调用会带来额外性能开销。
五、示例代码
#include<iostream>
#include <vector>
#include <string>
#include <mutex>
using namespace std;
class Target;//抽象适配器类
class Adapter;//具体适配器类
class Adaptee;//适配者类
class Target {
public:
virtual ~Target() {};
virtual void todo() = 0;
};
class Adaptee {
public:
~Adaptee() {}
void dosomthing() {
cout << "Adaptee::dosomthing()" << endl;
}
};
class Adapter : public Target{
public:
Adapter() : adaptee(make_shared<Adaptee>()) {};
~Adapter() {};
void todo() override {
adaptee->dosomthing();
};
private:
shared_ptr<Adaptee> adaptee;
};
int main() {
shared_ptr<Target> target = make_shared<Adapter>();
target->todo();
}