一、适配器模式简介(Brief Introduction)
适配器模式,将一个类装换成客户期望的另外一个接口。Adapter模式使的原本由于接口不兼容而不能工作的那些类可以一起工作。
二、解决的问题(What To Solve)
1、使用第三方组件,而这个组件的接口与目前系统接口不兼容(如方法与系统方法不一致等),可以使用适配器模式解决接口不兼容问题。
2、使用早前项目一些有用的类,可以用适配器模式解决现有接口与原有对象接口不兼容问题。
三、分类
类适配器和对象适配器
四、类功能简述
Client:客户端,调用自己需要的领域接口Target
Target:定义客户端需要的跟特定领域相关的接口
Adaptee:已经存在的接口,通常能满足客户端的功能要求,但是接口与客户端要求的特定领域接口不一致,需要被适配
Adapter:适配器,把Adaptee适配成为Client需要的Target
五、类适配器
1、客户需要的接口Target
class Target
{
public:
virtual void request(int i) = 0;
};
2、原有的功能接口Adaptee
/**
**被适配的类,通常是已经存在的类
**/
class Adaptee
{
public:
/**
**已经存在的接口,通常能满足客户端新需求的功能要求,但是在
**但是接口与客户端新需求的接口不一致,需要被适配
**/
void specificRequest()
{
std::cout << "Handing specificRequest..." << std::endl;
}
};
3、类适配器Adapter
/**
**类适配器:需要public继承Target,而private继承Adaptee,因为不希望Adaptee旧的接口被暴露出去
**/
class Adapter:public Target,private Adaptee
{
public:
/**
**新需求所需要的接口发生了变化,但是原有的接口还有用,因此要适配
**/
virtual void request(int i)
{
std::cout << "before handle specific request,print i:" << i << std::endl;
specificRequest();
}
};
4、客户端Client
int main()
{
Adapter adapter;
adapter.request(121);
Target *target = new Adapter();
target->request(212);
}
六、对象适配器
只需要重写Adapter即可,其他的相同
/**
**对象适配器:被适配类Adaptee作为适配器的一个成员变量
**/
class ObjectAdapter:public Target
{
public:
ObjectAdapter()
{
adaptee = new Adaptee();
}
/**
**新需求所需要的接口发生了变化,但是原有的接口还有用,因此要适配
**/
virtual void request(int i)
{
std::cout << "before handle specific request,print i:" << i << std::endl;
adaptee->specificRequest();
}
private:
Adaptee *adaptee;
};
七、输出结果
before handle specific request,print i:121
Handing specificRequest...
before handle specific request,print i:212
Handing specificRequest...