【設計模式】命令模式

來源:互聯網
上載者:User

標籤:style   blog   http   使用   os   io   for   2014   

命令模式:將請求封裝在對象中,客戶不直接調用某個對象的方法,而是使用命令,將命令傳遞給擁有方法的對象從而讓某一方法被調用。UML圖如下:



下面是用C++描寫的命令模式的一個簡單例子:

#include <iostream>#include <string>#include <list>using namespace std;// Interfaceclass 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章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.