Command模式

xiaoxiao2021-02-28  94

在开发中,有时需要向对象发送请求,但是不知道请求的接受者是谁,被请求的操作是什么.这时可以使用Command模式.

Command模式将请求封装到一个对象(Command)中,并将请求的接受者存放到具体的ConcreteCommand类中的Receiver中.这样实现了操作的对象和操作的具体实现之间的解耦.

实现

//Receiver.h

#ifndef _RECIEVER_H_ #define _RECIVEER_H_ class Reciever { public: Reciever(); ~Reciever(); void Action(); }; #endif

//Receiver.cpp

#ifndef _RECIEVER_H_ #define _RECIVEER_H_ class Reciever { public: Reciever(); ~Reciever(); void Action(); }; #endif

//Command.h

#ifndef _COMMAND_H_ #define _COMMAND_H_ class Reciever; class Command { public: virtual ~Command(); virtual void Excute() = 0; protected: Command(); }; class ConcreteCommand :public Command { public: ConcreteCommand(Reciever* rev); ~ConcreteCommand(); void Excute(); private: Reciever* rev_; }; #endif

//Command.cpp

#include "Command.h" #include "Reciever.h" #include <iostream> Command::Command() {} Command::~Command() {} ConcreteCommand::ConcreteCommand(Reciever* rev) { rev_ = rev; } ConcreteCommand::~ConcreteCommand() { delete rev_; rev_ = NULL; } void ConcreteCommand::Excute() { rev_->Action(); }

//Invoke.h

#ifndef _INVOKER_H_ #define _INVOKER_H_ class Command; class Invoker { public: Invoker(Command* cmd); ~Invoker(); void Invoke(); private: Command* cmd_; }; #endif

//Invoke.cpp

#include "Command.h" #include "Invoker.h" #include <iostream> Invoker::Invoker(Command* cmd) { cmd_ = cmd; } Invoker::~Invoker() { delete cmd_; cmd_ = NULL; } void Invoker::Invoke() { cmd_->Excute(); }

//main.cpp

#include "Command.h" #include "Invoker.h" #include "Reciever.h" int main() { Reciever* rev = new Reciever(); Command* cmd = new ConcreteCommand(rev); Invoker* inv = new Invoker(cmd); inv->Invoke(); return 0; }
转载请注明原文地址: https://www.6miu.com/read-54607.html

最新回复(0)