适配器模式
- 将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
例子1
5v电压抽象类
class V5
{
public:
virtual void useV5() = 0;
};
//目前只有v220的类 没有v5
class V220
{
public:
void useV220() {
cout << "使用了220v的电压" << endl;
}
};
//定义一个中间的适配器类-输入220v电压,输出5v电压
class Adapter :public V5
{
public:
Adapter(V220 * v220)
{
this->v220 = v220;
}
~Adapter() {
if (this->v220 != NULL) {
delete this->v220;
}
}
virtual void useV5() {
v220->useV220(); //调用需要另外的方法
cout << "输出5v电压" << endl;
}
private:
V220 *v220;
};
手机类->使用5v进行充电
class iphone
{
iPhone(V5* v5)
{
this->v5=v5;
}
~iPhone()
{
if (this->v5 != NULL) {
delete this->v5;
}
}
void charge()
{
v5-useV5();
cout << "iphone手机充电中"<< endl;
}
private:
V5* v5;
};
调用:220v电压经过适配器再传给iPhone
int main(void)
{
iPhone *phone = new iPhone(new Adapter(new V220));
phone->charge();
return 0;
}
例子2
实现一个绑定适配器,Bind2nd
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//Print输入参数是2个,不能接受for_each算法(1个)的参数
class Print
{
public:
void operator()(int v1, int v2)
{
cout << v1 + v2 << endl;
}
};
//适配器抽象类,实现适配成一个参数
class Target
{
public:
virtual void operator()(int arg) = 0;
};
//适配器类的实现
class Adapter:public Target
{
public:
Adapter(int para)
{
this->parm = para;
}
virtual void operator()(int arg)
{
print(arg,parm); //arg 是for_each传入参数,parm是调用适配器时自己给的值
}
private:
int parm;
Print print;
};
Adapter MyBind2nd(int v)
{
return Adapter(v);
}
int main(void)
{
vector<int> v1;
for (int i = 0; i < 5; i++)
{
v1.push_back(i);
}
for_each(v1.begin(), v1.end(), MyBind2nd(100));//vector每个元素和 传入100的绑定
return 0;
}
结果:实现了 vector每个元素和 传入100的绑定
- 优点:
(1)使得目标类和适配者类解耦,通过适配器重用适配者类,无需修改原结构
(2)增加类的透明性,将具体业务交给适配者,对于客户端透明。
(3)提高灵活性,可扩展性。方便跟换适配器,不修改源码,增加新的适配器。
- 缺点:
(1)过多地使用适配器,会让系统非常零乱,不易整体进行把握。
(2)适配器中实现适配者类的某些方法比较麻烦。
- 使用场景:
系统需要使用一些类,而这些类的接口不符合系统需求。