1. 概述
Adapter pattern即适配器模式,其主要用于:
1) 一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
2)给一个现存的类提供一个新的接口
3)包装现有类,使其能使用新的系统
Adapter pattern 类图:
Client:定义客户请求接口
Adaptee:需要进行适配的类
Adapter:适配器
2.实例
餐馆每天早上8点开张,老板只要告诉经理,开张,经理就会吩咐让厨师开始准备食物,服务员把门打开。
代码:
Cook preprare food
Waiter open the door
Adapter pattern即适配器模式,其主要用于:
1) 一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
2)给一个现存的类提供一个新的接口
3)包装现有类,使其能使用新的系统
Adapter pattern 类图:
Adaptee:需要进行适配的类
Adapter:适配器
2.实例
餐馆每天早上8点开张,老板只要告诉经理,开张,经理就会吩咐让厨师开始准备食物,服务员把门打开。
代码:
#include <iostream>
//Target接口
class Open_interface
{
public:
virtual ~Open_interface()
{
}
virtual void open() = 0;
};
//Adapter
template <class TYPE>
class Manage : public Open_interface
{
public:
Manage(TYPE* type, void(TYPE:: *d)())
{
_type = type;
_do = d;
}
~Manage()
{
if(_type)
{
delete _type;
_type = NULL;
}
}
void open()
{
(_type->*_do)();
}
private:
TYPE* _type;
void(TYPE:: *_do)();
};
//adaptee
class Cook
{
public:
void prepare_food()
{
std::cout << "Cook preprare food" << std::endl;
}
};
//adaptee
class Waiter
{
public:
void open_door()
{
std::cout << "Waiter open the door" << std::endl;
}
};
//client
int main()
{
Open_interface **group = new Open_interface *[2];
group[0] = new Manage<Cook> (new Cook(), &Cook::prepare_food);
group[1] = new Manage<Waiter> (new Waiter(), &Waiter::open_door);
for(int i = 0; i < 2; i++)
{
group[i] -> open();
}
for(int i = 0; i < 2; i++)
{
if(group[i])
{
delete group[i];
}
}
delete group;
return 0;
}
输出:
Cook preprare food
Waiter open the door