测试用例:
[code]int main(){ barbecuer boy; bakechickenwingcommand bakechickenwingcommand1(boy); bakechickenwingcommand bakechickenwingcommand2(boy); bakemuttoncommand bakemuttoncommand1(boy); bakemuttoncommand bakemuttoncommand2(boy); waiter girl; girl.setorder(&bakechickenwingcommand1); girl.setorder(&bakechickenwingcommand2); girl.setorder(&bakemuttoncommand1); girl.setorder(&bakemuttoncommand2); girl.notify(); girl.cancelorder(&bakechickenwingcommand2); girl.notify(); return 0; }
类实现:
[code]class barbecuer{ public: void bakemutton() { cout << "meat\n"; } void bakechickenwing() { cout << "chicken\n"; } }; class command{ protected: barbecuer receiver; public: command(){} command(barbecuer & b) :receiver(b){} virtual void excutecommand() = 0; }; class bakemuttoncommand :public command{ public: bakemuttoncommand(barbecuer & b) { receiver = b; } void excutecommand(){ receiver.bakemutton(); } }; class bakechickenwingcommand :public command{ public: bakechickenwingcommand(barbecuer & b) { receiver = b; } void excutecommand(){ receiver.bakechickenwing(); } }; class waiter{ list<command *>orders; public: void setorder(command * comptr); void cancelorder(command * comptr); void notify(); }; void waiter::setorder(command * comptr){ orders.push_back(comptr); cout << "add order\n"; } void waiter::cancelorder(command * comptr){ orders.remove(comptr); cout << "cancel order\n"; } void waiter::notify(){ for each (command * var in orders){ var->excutecommand(); } }
总结:
较容易的设计一个命令队列;
在需要的情况下,可以较容易地将命令记入日志;
允许接收请求的一方决定是否否决请求;
可以容易地实现对请求的撤销和重做;
由于加进新的命令类不影响其他的类,因为增加新的具体命令类很容易。
命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开
以上就是c++设计模式浅识命令模式的内容。