在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类别自己的接口包裹在一个已存在的类中。
结构图
适配器模式分为类适配器模式和对象适配器模式。
类适配器模式结构图
c++代码示例:
#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
virtual void Request() {};
};
// "Adaptee"
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout<<"Called SpecificRequest()"<<endl;
}
};
// "Adapter"
class Adapter : public Adaptee, public Target
{
public:
// Implements ITarget interface
void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
this->SpecificRequest();
}
};
int main() {
// Create adapter and place a request
Target * t = new
Adapter();
t->Request();
return 0;
}
对象适配器结构图:
c++代码示例
#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
virtual void Request() {};
};
// "Adaptee"
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout<<"Called SpecificRequest()"<<endl;
}
};
// "Adapter"
class Adapter : public Target
{
private:
Adaptee *adaptee;
public:
Adapter()
{
adaptee = new Adaptee();
}
// Implements ITarget interface
void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
adaptee->SpecificRequest();
}
};
int main() {
// Create adapter and place a request
Target * t = new
Adapter();
t->Request();
return 0;
}
缺省适配器c++代码实例:
#include<iostream>
using namespace std;
class Target {
public:
virtual void f1() {};
virtual void f2() {};
virtual void f3() {};
};
class DefaultAdapter : public Target
{
public:
void f1() {
}
void f2() {
}
void f3() {
}
};
class MyInteresting :public DefaultAdapter
{
public:
void f3() {
cout<<"呵呵,我就对f3()方法感兴趣,别的不管了!"<<endl;
}
};
int main() {
// Create adapter and place a request
Target * t = new
MyInteresting();
t->f3();
return 0;
}
拓展连接:
http://www.cnblogs.com/qianxudetianxia/archive/2012/02/27/2010965.html
http://liuling123.com/2013/04/object-adapter.html