标签:style blog http color io os for 2014 div
命令模式中,命令抽象成一个借口,包含一个命令的执行者,能够派生出各种不同的命令。并有一个命令的管理者,能够添加各种命令,添加完后,在必要的时候通知执行者执行这些命令。
Command.h内容
1 #ifndef Command_H_H 2 #define Command_H_H 3 4 #include <iostream> 5 #include <vector> 6 using namespace std; 7 8 9 class Cooker 10 { 11 public: 12 void makeIce() { cout << "Make a Ice!" << endl; } 13 void makeJuice() { cout << "Make a Juice!" << endl; } 14 }; 15 16 class Command 17 { 18 public: 19 Command() : cooker(NULL) {} 20 virtual void excute() = 0; 21 virtual ~Command() {} 22 void setCooker(Cooker *cooker0) { cooker = cooker0; } 23 protected: 24 Cooker *cooker; 25 }; 26 27 class CommandIce : public Command 28 { 29 public: 30 virtual void excute() { cooker->makeIce(); } 31 }; 32 33 class CommandJuice : public Command 34 { 35 public: 36 virtual void excute() { cooker->makeJuice(); } 37 }; 38 39 class Waiter 40 { 41 public: 42 Waiter() : cooker(NULL) {} 43 void addCommand(Command *command){ 44 command->setCooker(cooker); 45 vecCommand.push_back(command); 46 } 47 void sendCommand(){ 48 for(size_t i=0; i<vecCommand.size(); ++i){ 49 vecCommand[i]->excute(); 50 } 51 } 52 void setCooker(Cooker *cooker0) { cooker = cooker0; } 53 54 private: 55 vector<Command*> vecCommand; 56 Cooker* cooker; 57 }; 58 59 60 61 void CommandTest() 62 { 63 Cooker *cooker = new Cooker(); 64 Waiter *waiter = new Waiter(); 65 waiter->setCooker(cooker); 66 67 Command *command1 = new CommandIce(); 68 Command *command2 = new CommandJuice(); 69 waiter->addCommand(command1); 70 waiter->addCommand(command2); 71 72 waiter->sendCommand(); 73 delete waiter; 74 delete cooker; 75 } 76 77 #endif
运行结果:
实例中,Waiter是命令的管理者,Cooker是命令执行者,添加makeIce和makeJuice两种命令并执行。
标签:style blog http color io os for 2014 div
原文地址:http://www.cnblogs.com/MiniHouse/p/3983108.html