餐馆那些事之:Adapter Pattern

1. 概述
Adapter pattern即适配器模式,其主要用于:
1) 一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
2)给一个现存的类提供一个新的接口
3)包装现有类,使其能使用新的系统
Adapter pattern 类图:

Client:定义客户请求接口
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值