#include "stdafx.h" #include <iostream> #include <vector> using namespace std; class Barbecuer { public: void BakeMutton() { cout << "Bake Mutton!" << endl; } void BakeChickenWing() { cout << "Bake ChickenWing!" << endl; } }; class Command { public: virtual ~Command(){} Command(Barbecuer* barbecuer) { m_Barbecuer = barbecuer; } virtual void ExcuteCommand() = 0; protected: Barbecuer* m_Barbecuer; }; class BakeMuttonCommand :public Command { public: BakeMuttonCommand(Barbecuer* barbecuer) : Command(barbecuer) {} virtual void ExcuteCommand() { m_Barbecuer->BakeMutton(); } }; class BakeChickenWingCommand :public Command { public: BakeChickenWingCommand(Barbecuer* barbecuer) : Command(barbecuer) {} virtual void ExcuteCommand() { m_Barbecuer->BakeChickenWing(); } }; class Waiter { private: vector<Command*> orders; public: void SetOrder(Command* command) { if (true) //可以对请求进行拒绝 { orders.push_back(command); cout << "日志:add order" <<endl; } } void CancelOrder(Command* command) { vector<Command*>::iterator it = find(orders.begin(), orders.end(), command); orders.erase(it); } void Notify() { for each (Command* var in orders) { var->ExcuteCommand(); } } };// CommandPattern.cpp
// CommandPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Command.h" int _tmain(int argc, _TCHAR* argv[]) { Barbecuer* boy = new Barbecuer(); Command* MuttonCommand = new BakeMuttonCommand(boy); Command* ChickenCommand = new BakeChickenWingCommand(boy); Waiter girl; cout << "点菜吧" << endl; girl.SetOrder(MuttonCommand); girl.SetOrder(MuttonCommand); girl.SetOrder(ChickenCommand); cout << "做菜吧" << endl; girl.Notify(); cout << "不要羊肉了" << endl; girl.CancelOrder(MuttonCommand); girl.Notify(); getchar(); return 0; }
原文:http://blog.csdn.net/wwwdongzi/article/details/27097899