【设计模式】命令模式
生活随笔
收集整理的這篇文章主要介紹了
【设计模式】命令模式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
命令模式:將請(qǐng)求封裝在對(duì)象中,客戶不直接調(diào)用某個(gè)對(duì)象的方法,而是使用命令,將命令傳遞給擁有方法的對(duì)象從而讓某一方法被調(diào)用。UML圖例如以下:
以下是用C++描寫的命令模式的一個(gè)簡單樣例:
#include <iostream> #include <string> #include <list>using namespace std;// Interface class Command { public:virtual void Execute() = 0; };/* Invoker命令發(fā)送者 */ class Switch { public:// 存儲(chǔ)命令void Add(Command *command){commands.push_back(command);}// 刪除命令void Remove(Command *command){commands.remove(command);}// 運(yùn)行全部命令的發(fā)送void Execute(){list<Command*>::iterator iter = commands.begin();for (; iter != commands.end(); ++iter){(*iter)->Execute();}}private:list<Command*> commands; };/* The Receiver class */ class Light { public:void TurnOn(){cout << "The light is on" << endl;}void TurnOff(){cout << "The light is off" << endl;} };/* The Command for turning on the light - ConcreteCommand #1 */ class FlipUpCommand : public Command { public:FlipUpCommand(Light light){light = light;}void Execute(){light.TurnOn();} private:Light light; // 命令中包括命令接收者 };/* The Command for turning off the light - ConcreteCommand #2 */ class FlipDownCommand : public Command { public:FlipDownCommand(Light light){light = light;}void Execute(){light.TurnOff();} private:Light light; // 命令中包括命令接收者 };int main() {Light light; // 燈有‘開’、‘關(guān)’兩種操作Command *up = new FlipUpCommand(light); // ‘開’命令Command *down = new FlipDownCommand(light); // ‘關(guān)’命令Switch sw;sw.Add(up); // 命令交給開關(guān)sw.Add(down); // 命令交給開關(guān)sw.Execute(); // 開關(guān)運(yùn)行命令sw.Remove(up);sw.Execute(); // 開關(guān)運(yùn)行命令system("pause");return 0; }
執(zhí)行結(jié)果:
命令被封裝成類,然后由某個(gè)Invoker(這里是switch開關(guān)類)保存、刪除、發(fā)出命令。命令行的長處在于:把請(qǐng)求一個(gè)操作的對(duì)象(Invoker)與知道怎么運(yùn)行一個(gè)操作的對(duì)象(Receiver)分隔開了。我們能夠在實(shí)際操作開始之前或之后進(jìn)行某些靈活的操作,比方:加入、刪除、反復(fù)、記錄日志等。
參考:
維基百科
《大話設(shè)計(jì)模式》第23章
轉(zhuǎn)載于:https://www.cnblogs.com/mfrbuaa/p/4083830.html
總結(jié)
以上是生活随笔為你收集整理的【设计模式】命令模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .net 测试工具类
- 下一篇: 在ASP.NET项目中使用CKEdito