意图:将一个类的接口转换成客户希望的另一种接口,从而使原本接口不兼容而无法在一起工作的那些类能够在一起工作。
适配器模式分为:类适配器模式和对象适配器模式。
类适配器模式
客户端需要实现SpecificRequest()操作,但是需要Request()方法,为了使客户能够使用Adaptee类,提供一个中间环节(Adapter类),Adapter类继承自Adaptee,Adapter类的Request方法重新封装了Adaptee的SpecificRequest方法,实现了适配的目的。
对象适配器模式
客户端需要实现SpecificRequest()操作,但是需要Request()方法,为了使客户端能够使用Adaptee类,提供一个中间环节(Adapter类),这个类包装了一个Adaptee的实例,从而将客户端与Adaptee衔接起来。
类适配器模式C++实现
#include<iostream>
using namespace std;
class Target
{
public:
virtual void Request(){};
};
class Adaptee
{
public:
void SpecificRequest()
{
cout<<"Called SpecificRequest()"<<endl;
}
};
class Adapter : public Adaptee, public Target
{
public:
void Request()
{
this->SpecificRequest();
}
};
int main()
{
Target *t = new Adapter();
t->Request();
return 0;
}
对象适配器模式C++实现
#include<iostream>
using namespace std;
class Target
{
public:
virtual void Request(){};
};
class Adaptee
{
public:
void SpecificRequest()
{
cout<<"Called SpecificRequest()"<<endl;
}
};
class Adapter : public Target
{
private:
Adaptee *adaptee;
public:
Adapter()
{
adaptee = new Adaptee();
}
void Request()
{
adaptee->SpecificRequest();
}
};
int main()
{
Target *t = new Adapter();
t->Request();
return 0;
}