標籤: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章