命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
#include <iostream> using namespace std; //Receiver类,知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者 class Receiver { public: void Action() { cout << "执行请求" << endl; } }; //Command类,用来声明执行操作的接口 class Command { protected: Receiver *m_receiver; public: Command(Receiver *receiver) { this->m_receiver=receiver; } virtual void Execute(){} }; //ConcreteCommand类,将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现Execute class ConcreteCommand:public Command { public: ConcreteCommand(Receiver *receiver):Command(receiver){} void Execute() { m_receiver->Action(); } }; //Invoker类,要求该命令执行这个请求 class Invoker { private: Command *m_command; public: void SetCommand(Command *command) { this->m_command=command; } void ExecuteCommand() { m_command->Execute(); } }; int main() { Receiver *r=new Receiver(); Command *c=new ConcreteCommand(r); Invoker *i=new Invoker(); i->SetCommand(c); i->ExecuteCommand(); return 0; }
命令模式的优点:1.它能较容易地设计一个命令队列;2.在需要的情况下,可以较容易地将命令记入日志;3.允许接收请求的一方决定是否要否决请求;4.可以容易地实现对请求的撤销和重做;5,由于加进新的具体命令类不影响其他的类,因此增加新的具体命令类很容易;6.最关键的优点,命令模式把请求一个操作对象与知道怎么执行一个操作的对象分割开。
举个例子:
#include <iostream> #include <list> using namespace std; class Barbecuer { public: void BakeMutton() { cout << "烤羊肉串!" << endl; } void BakeChickenWing() { cout << "烤鸡翅" << endl; } }; class Command { protected: Barbecuer *m_receiver; public: Command(Barbecuer *receiver) { this->m_receiver=receiver; } virtual void ExecuteCommand()=0; }; class BakeMuttonCommand:public Command { public: BakeMuttonCommand(Barbecuer *receiver):Command(receiver){} void ExecuteCommand() { m_receiver->BakeMutton(); } }; class BakeChickenWingCommand:public Command { public: BakeChickenWingCommand(Barbecuer *receiver):Command(receiver){} void ExecuteCommand() { m_receiver->BakeChickenWing(); } }; class Waiter { private: list<Command*> m_commandList; public: void SetCmd(Command *temp) { m_commandList.push_back(temp); cout << "增加订单" << endl; } void Notify() { list<Command*>::iterator iter=m_commandList.begin(); for(;iter!=m_commandList.end();iter++) (*iter)->ExecuteCommand(); } }; int main() { Barbecuer *boy=new Barbecuer(); Command *bakeMuttonCommand1=new BakeMuttonCommand(boy); Command *bakeMuttonCommand2=new BakeMuttonCommand(boy); Command *bakeChickenWingCommand1=new BakeChickenWingCommand(boy); Waiter *girl=new Waiter(); girl->SetCmd(bakeMuttonCommand1); girl->SetCmd(bakeMuttonCommand2); girl->SetCmd(bakeChickenWingCommand1); girl->Notify(); return 0; }