C++设计模式_命令模式练习代码

C++设计模式_命令模式练习代码,自己写的简单的一个代码,留着以后备忘。

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include <list>

using namespace std;

// 烤串师傅
class Cooker {
public:
	void makeChicken() {
		cout << "烤串师傅 烤了 鸡肉" << endl;
	}
	void makeChuaner() {
		cout << " 烤串师傅 烤了 羊肉串 " << endl;
	}
};

//抽象的命令
class Command {
public:
	Command(Cooker *cooker) {
		this->cooker = cooker;
	}

	~Command() {
		if (this->cooker != NULL) {
			delete cooker;
		}
	}

	//菜单的执行命令
	virtual void execute() = 0;

protected:
	Cooker* cooker;
};
//具体的 羊肉串命令
class CommandChuaner:public Command {
public:
	CommandChuaner(Cooker *cooker) : Command(cooker) {}

	//菜单的执行命令
	virtual void execute() {
		this->cooker->makeChuaner();
	}
};
//具体的 鸡肉命令
class CommandChicken :public Command {
public:
	CommandChicken(Cooker *cooker) : Command(cooker) {}

	//菜单的执行命令
	virtual void execute() {
		this->cooker->makeChicken();
	}
};
class Waitress {
public:
	Waitress() {
		cmd_list.clear();
	}
	//添加命令的方法
	void setCmd(Command * cmd) {
		this->cmd_list.push_back(cmd);
	}
	//批量执行命令
	void notify() {
		for (list<Command* >::iterator it = cmd_list.begin(); it != cmd_list.end(); it++) {
			(*it)->execute();
		}
	}
private:
	list<Command* > cmd_list;
};

int main(void)
{
	Waitress *mm = new Waitress;

	//点餐
	Command *cmdChuaner = new CommandChuaner(new Cooker);
	Command *cmdChicken = new CommandChicken(new Cooker);

	mm->setCmd(cmdChicken);
	mm->setCmd(cmdChuaner);
	//下单
	mm->notify();
	delete mm;
	return 0;
}

 

庄朋龙
庄朋龙

一个爱生活的技术菜鸟

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注