设计模式之命令模式(二)
将命令的操作类抽象出来,作为参数传递给命令类的对象。
命令的操作类
#pragma once class Reciever { public: Reciever(); ~Reciever(); void Action(); };
#include "Reciever.h" #include <iostream> Reciever::Reciever() { } Reciever::~Reciever() { } void Reciever::Action() { std::cout << "Reciever action ..." << std::endl; return; }
命令类
#pragma once class Command { public: virtual ~Command(); virtual void Excute() = 0;//派生类实现 protected: Command(); };
#include "Command.h" Command::Command() { } Command::~Command() { }
命令类的派生类
#pragma once #include "Command.h" template <class Reciever> class SimpleCommand : public Command { public: typedef void(Reciever::*Interface_Pointer)(); SimpleCommand(Reciever *rev, Interface_Pointer act); ~SimpleCommand(); virtual void Excute(); private: Reciever *m_rec; Interface_Pointer m_Interface; };
#include "SimpleCommand.h" #include "Reciever.h" template <class Reciever> SimpleCommand<Reciever>::SimpleCommand(Reciever *rev, Interface_Pointer act) { m_rec = rev; m_Interface = act; } template <class Reciever> SimpleCommand<Reciever>::~SimpleCommand() { } template <class Reciever> void SimpleCommand<Reciever>::Excute() { (m_rec->*m_Interface)(); return; }
测试
#include <iostream> #include "SimpleCommand.h" #include "SimpleCommand.cpp"//模板类 #include "Reciever.h" int main() { Reciever *rev = new Reciever(); Command *cmd = new SimpleCommand<Reciever>(rev, &Reciever::Action); cmd->Excute(); if (cmd) { delete cmd; cmd = NULL; } if (rev) { delete rev; rev = NULL; } std::cout << "Hello World!\n"; }

浙公网安备 33010602011771号