命令模式(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++設計模式淺識命令模式的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!