Adaptee类没有Request方法,而客户期待这个方法。为了使客户能够使用Adaptee类,提供一个中间环节,即类Adapter类,Adapter类实现了Target接口,并继承自Adaptee,Adapter类的Request方法重新封装了Adaptee的SpecificRequest方法,实现了适配的目的。
角色包括:
目标(Target)角色:这是客户所期待的接口。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类
继承实现的UML图:
#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
virtual void Request(){}
};
// "Adaptee"
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout<<"CalledSpecificRequest()"<<endl;
}
};
// "Adapter"
class Adapter : public Adaptee, public Target
{
public:
// Implements ITargetinterface
void Request()
{
//Possibly do some data manipulation
// andthen call SpecificRequest
this->SpecificRequest();
}
};
int main()
{
// Create adapter and place arequest
Target *t = newAdapter();
t->Request();
return0;
}
#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
virtual void Request(){}
};
// "Adaptee"
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout<<"CalledSpecificRequest()"<<endl;
}
};
// "Adapter"
class Adapter : public Target
{
private:
Adaptee *adaptee;
public:
Adapter()
{
adaptee =new Adaptee();
}
~ Adapter() //为防止内存泄露,本人在原代码的基础上添加的
{
if(NULL!= adaptee)
delete adaptee;
adaptee=NULL;
}
// Implements ITargetinterface
void Request()
{
//Possibly do some data manipulation
// andthen call SpecificRequest
adaptee->SpecificRequest();
}
};
int main()
{
// Create adapter and place arequest
Target *t = new Adapter();
t->Request();
return0;
}