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