意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。
代码:
#include <iostream> #include <list> using namespace std; // 厨师 class Cook { public: void cookChicken() { cout << "cook chicken" << endl; } void cookBeef() { cout << "cook beaf" << endl; } }; class Command { public: virtual ~Command() {} Command(Cook *c) :_cook(c) {} public: virtual void executeCmd() = 0; protected: Cook *_cook; }; class CookChicken : public Command { public: CookChicken(Cook *c) :Command(c){}
public: virtual void executeCmd() { _cook->cookChicken(); } }; class CookBeef : public Command { public: CookBeef(Cook *c) :Command(c){} public: virtual void executeCmd() { _cook->cookBeef(); } }; class Waiter { public: Waiter() { _commandList.clear(); } ~Waiter() { _commandList.clear(); } void addOrder(Command *c) { cout << "增加订单" << endl; _commandList.push_back(c); } void notify() { for (auto it = _commandList.begin(); it != _commandList.end(); ++it) { (*it)->executeCmd(); } _commandList.clear(); } private: list<Command *> _commandList; }; void test() { Cook *cook = new Cook(); // 厨师 Waiter *waiter = new Waiter(); // 服务员 Command *cmd1 = new CookChicken(cook); Command *cmd2 = new CookBeef(cook); waiter->addOrder(cmd1); waiter->addOrder(cmd2); waiter->notify(); // 发送通知 delete cook; delete waiter; delete cmd1; delete cmd2; } int main() { test(); cin.get(); return 0; }
效果: