设计模式-行为-Command(命令)模式
将行为的请求者 和 执行者 解耦,从而适应像 撤销/重做 等处理需求。
实现起来也很简单,吧请求封装到一个类(Command)中,在提供处理对象(Receiver)最后由Invoke调用。
- 我们可以通过回调的方式 吧处理请求的 处理对象封装为 参数 传递到到command中,可用函数指针也可用匿名函数。
- 处理对象(Receiver)可以用多个处理函数,来处理不同的命令。
- 处理对象(Receiver)还可以只有一个处理函数,通过传参 RTTI 来确定具体的操作。实现统一的处理接口
例1
class Receiver { public: virtual void Action() { cout << __FUNCTION__ << endl; } }; class Command { public: virtual void Execute() = 0; protected: Receiver*recver; }; class ConCreateCommand :public Command { public: virtual void Execute()override { recver->Action(); } ConCreateCommand(Receiver*recevier) { this->recver = recevier; } }; class Invoker { public: void Invoke() { command->Execute(); } Invoker(Command *com) { this->command = com; } private: Command*command; }; void testCommand() { Receiver *recv = new Receiver; ConCreateCommand *com = new ConCreateCommand(recv); Invoker *invoke = new Invoker(com); invoke->Invoke(); }
例2
class ReceverTV { public: void ActionVolumeUp() { cout << __FUNCTION__ << endl; } void ActionPowerOn() { cout << __FUNCTION__ << endl; } }; class Command { public: virtual void Execute() = 0; protected: ReceverTV *recv; }; class CommandOn :public Command { public: virtual void Execute()override { cout << "power on" << endl; recv->ActionPowerOn(); } CommandOn(ReceverTV *tv) { recv = tv; } }; class CommandVolumeUp :public Command { public: virtual void Execute() { cout << "volume up" << endl; recv->ActionVolumeUp(); } CommandVolumeUp(ReceverTV *tv) { recv = tv; } }; class Invoker { public: void Invoke() { com->Execute(); } Invoker(Command *com) { this->com = com; } private: Command*com; }; void testCommand2() { ReceverTV*tv = new ReceverTV(); auto *on = new CommandVolumeUp(tv); Invoker *invoke = new Invoker(on); invoke->Invoke(); } void testCommand3() { ReceverTV*tv = new ReceverTV(); auto *on = new CommandVolumeUp(tv); on->Execute(); }
例3
#include <functional> class Receiver { public: virtual void Action() { cout << __FUNCTION__ << endl; } }; class Command { public: virtual void Execute() = 0; }; class CallbackCommand :public Command { public: virtual void Execute()override { if (recever) recever(); } CallbackCommand(const std::function<void(void)>& recever) { this->recever = recever; } private: std::function<void(void)> recever = nullptr; }; void testCommand4() { Receiver *rev = new Receiver; Command *com = new CallbackCommand([=]() { rev->Action(); }); com->Execute(); //RTTI // cout << typeid(com).hash_code(); cout << (unsigned int)(com) << endl;; { Receiver *rev = new Receiver; Command *com = new CallbackCommand([=]() { rev->Action(); }); com->Execute(); //RTTI //cout << typeid(com).hash_code(); cout << (unsigned int)(com) << endl; } // cout << (unsigned int)(com); }