适配器模式(Adapter Pattern)
flyfish
Convert the interface of a class into another interface clients
expect. Adapter lets classes work together that couldn’t otherwise
because of incompatible interfaces.将一个类的接口变成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一个工作的两个类能够在一起工作。
《设计模式之禅》举了个很好的例子 该模式就像笔记本电脑上的电源适配器,电压可以在110V-220V之间变化,以适应不同的笔记本电脑
#include "stdafx.h"
#include <iostream>
using namespace std;
//目标角色
class Target
{
public:
virtual void Request(){cout<<"Target::Request"<<endl;}
};
//目标角色的实现类
class ConcreteTarget: public Target
{
public:
virtual void Request(){cout<<"ConcreteTarget::Request"<<endl;}
};
//原角色
class Adaptee
{
public:
void DoSomething(){cout<<"Adaptee::DoSomething"<<endl;}
};
//适配器角色
class Adapter : public Adaptee, public Target
{
public:
void Request()
{
cout<<"Adapter::DoSomething"<<endl;
DoSomething();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
//原有的业务逻辑
Target *a = new ConcreteTarget();
a->Request();
//增加了适配器之后
Target *b = new Adapter();
b->Request();
return 0;
}