适配器模式
将一个类的接口转换为客户希望的另外一个接口。Adapter
模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
UML
图如下:
适用性
-
你想使用一个已存在的类,而它的接口不符合你的需求。
-
你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作
-
你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配他们的接口,对象适配器可以适配它的父类接口
代码实现
//
// Created by andrew on 2020/11/17.
//
#include <iostream>
using namespace std;
class Current18v {
public:
virtual void useCurrent18v() = 0;
virtual ~Current18v() {
}
};
class Current220v {
public:
void useCurrent220v() {
cout << "使用 220v" << endl;
}
};
class Adapter : public Current18v {
public:
Adapter(Current220v *current) {
m_current = current;
}
virtual void useCurrent18v() {
cout << "适配 220v";
m_current->useCurrent220v();
}
private:
Current220v *m_current;
};
int main(int argc, char *argv[]) {
Current220v *current220v = NULL;
Adapter *adapter = NULL;
current220v = new Current220v;
adapter = new Adapter(current220v);
adapter->useCurrent18v();
delete adapter;
delete current220v;
return 0;
}
可以看到适配器做的工作就是讲220v
的电压,转化为用户需要的18v
电压。