命令模式-c++实现

总感觉这些设计模式有些唬人。。。不过解耦上还是有很大帮助的


// CommandPattern.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

//烤肉师父
class RoastCooK
{
public:
	void MakeMutton() { cout << "烤羊肉" << endl; }
	void MakeChickenWing() { cout << "烤鸡翅膀" << endl; }

};

//抽象命令
class Command
{
protected:
	RoastCooK * reciver;

public:
	Command(RoastCooK *temp) :reciver(temp) {}
	virtual void ExecuteCmd() = 0;
};

//烤肉命令
class MuttonCmd :public Command
{
public:
	MuttonCmd(RoastCooK *temp):Command(temp){}
	virtual void ExecuteCmd() { reciver->MakeMutton(); }
};

//烤鸡翅命令
class ChickenCmd: public Command
{
public:
	ChickenCmd(RoastCooK *temp):Command(temp){}
	virtual void ExecuteCmd() { reciver->MakeChickenWing(); }
};

//服务员类
class Waiter
{
protected:
	vector<Command*> m_command;

public:
	void SetCmd(Command* temp) { m_command.push_back(temp); }
	void Notify() 
	{
		vector<Command*>::iterator it;
		for (it = m_command.begin(); it != m_command.end(); ++it)
		{
			(*it)->ExecuteCmd();
		}
	}
};


int main()
{
	RoastCooK* cook = new RoastCooK();
	Command *cmd1 = new MuttonCmd(cook);
	Command *cmd2 = new ChickenCmd(cook);
	Waiter *waiter = new Waiter();

	//cmd
	waiter->SetCmd(cmd1);
	waiter->SetCmd(cmd2);

	waiter->Notify();

	//todo delete
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值