命令模式将一个请求封装为一个对象,从而使命令发出者可以用不同的请求对客户进行参数化;对请求排除或记录请求日志,以及支持可撤销的操作。
#include#include using namespace std;//命令接收者类class Receiver{public: void ActionA(string commandName) { cout << "Executing A, it's name is " << commandName << endl; } void ActionB(string commandName) { cout << "Executing B, it's name is " << commandName << endl; }};//命令抽象类class Command{protected: Receiver *receiver; //命令绑定的接收者 string commandName; //命令名称public: Command(Receiver *receiver, string commandName) { this->receiver = receiver; this->commandName = commandName; } virtual void Execute() = 0; //抽象命令执行方法(不同命令可以有不同的执行方法)};//具体命令Aclass CommandA: public Command{public: CommandA(Receiver *receiver, string commandName): Command(receiver, commandName) {} void Execute() //具体命令A执行方法 { receiver->ActionA(commandName); }};//具体命令Bclass CommandB: public Command{public: CommandB(Receiver *receiver, string commandName): Command(receiver, commandName) {} void Execute() //具体命令B执行方法 { receiver->ActionB(commandName); }};//命令发出者class Invoker{private: Command *command;public: void SetCommand(Command *command) //设置命令 { this->command = command; } void CancelCommand(Command *command) //撤销命令 { this->command = NULL; } void ExecuteCommand() //要求命令被执行 { if (command == NULL) return; command->Execute(); }};int main(){ Receiver *receiver = new Receiver(); //命令接收者 Invoker *invoker = new Invoker(); //命令发出者 Command *command1 = NULL; //命令A Command *command2 = NULL; //命令B command1 = new CommandA(receiver, "commandA"); invoker->SetCommand(command1); //命令发出者设置新命令 invoker->ExecuteCommand(); //命令发出者要求命令被执行 command2 = new CommandB(receiver, "commandB"); invoker->SetCommand(command2); invoker->ExecuteCommand(); return 0;}
1、可以设计一个命令队列;
2、在需要的情况下可以将命令记入日志;
3、允许接收命令的一方决定是否要否决命令;
4、可以容易地实现对命令的撤销和重做;
5、容易添加新的具体命令类。
命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开。