您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C++设计模式浅识命令模式

2024/8/15 20:10:53发布22次查看
命令模式(command)将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
测试用例:
[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++设计模式浅识命令模式的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product