总感觉这些设计模式有些唬人。。。不过解耦上还是有很大帮助的
// 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;
}