Command模式通过将请求封装到一个对象(command)中,并将请求的接受者存放到具体的ConcreteCommand类中(Receiver)中,从而实现调用操作的对象和操作的具体实现者的解耦。
场景应用:windows下的画图软件,画笔的undo/redo操作。
//Reciever.h #ifndef _RECIEVER_H_ #define _RECIEVER_H_ class Reciever { public: Reciever(); ~Reciever(); void Action(); protected: private: }; #endif //~_RECIEVER_H_
//Reciever.cpp #include "Reciever.h" #include <iostream> Reciever::Reciever() { } Reciever::~Reciever() { } void Reciever::Action() { std::cout<<"Reciever action......."<<std::endl; }
//Command.h #ifndef _COMMAND_H_ #define _COMMAND_H_ class Reciever; class Command { public: virtual ~Command(); virtual void Excute() = 0; protected: Command(); private: }; class ConcreteCommand : public Command { public: ConcreteCommand(Reciever* rev); ~ConcreteCommand(); void Excute(); protected: private: Reciever* _rev; }; #endif //~_COMMAND_H_
//Command.cpp #include "Command.h" #include "Reciever.h" #include <iostream> Command::Command() { } Command::~Command() { } void Command::Excute() { } ConcreteCommand::ConcreteCommand(Reciever* rev) { this->_rev = rev; } ConcreteCommand::~ConcreteCommand() { delete this->_rev; } void ConcreteCommand::Excute() { _rev->Action(); std::cout<<"ConcreteCommand..."<<std::endl; }
//Invoker.h #ifndef _INVOKER_H_ #define _INVOKER_H_ class Command; class Invoker { public: Invoker(Command* cmd); ~Invoker(); void Invoke(); protected: private: Command* _cmd; }; #endif //~_INVOKER_H_
//Invoker.cpp #include "Invoker.h" #include "Command.h" #include <iostream> Invoker::Invoker(Command* cmd) { _cmd = cmd; } Invoker::~Invoker() { delete _cmd; } void Invoker::Invoke() { _cmd->Excute(); }
//main.cpp #include "Command.h" #include "Invoker.h" #include "Reciever.h" #include <iostream> using namespace std; int main(int argc,char* argv[]) { Reciever* rev = new Reciever(); Command* cmd = new ConcreteCommand(rev); Invoker* inv = new Invoker(cmd); inv->Invoke(); system("pause"); return 0; }