首页 > 代码库 > 命令模式
命令模式
意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。
代码:
#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; }
效果:
命令模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。