适配器模式是一种结构性模式,它将一个类的接口转换成客户需要的接口,使得原来由于接口不兼容而不能一起工作的类可以一起工作
-
可以让没有关联的两个类一起运行
-
提高了类的复用性
- 过多适配器系统会比较乱,系统的维护性变差
- 当想使用已经存在的类,但是这个类的接口不符合客户需求
用户拿着适配器将两孔充电器转换成三孔
![适配器模式](https://img-blog.csdnimg.cn/20190713181159683.PNG)
#include <iostream>
// 三孔插座
class Three{
public:
void charging(){
std::cout << "三孔插座充电" << std::endl;
}
};
// 两孔充电器
class Two{
public:
void charging(){
std::cout << "两孔充电器充电" << std::endl;
}
};
// 适配器
class Adapter{
public:
void towToThree(){
two.charging();
std::cout << "两孔转三孔" << std::endl;
three.charging();
}
private:
Two two;
Three three;
};
int main(){
Adapter adapter;
adapter.towToThree();
return 0;
}