设计模式读书笔记:Command(命令)
2015-07-10 17:37:03
意图:
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Command
Command
namespace NS_COMMAND {
class Command {
public:
Command() {}
virtual ~Command() {}
virtual void execute(void) = 0;
};
template <class TReceiver>
class SimpleCommand : public Command {
public:
typedef void (TReceiver:: *Action)();
SimpleCommand(TReceiver *tr, Action act) : _treceiver(tr), _action(act) {}
virtual void execute(void);
private:
TReceiver *_treceiver;
Action _action;
};
template <class TReceiver>
void SimpleCommand<TReceiver>::execute() {
(_treceiver->*_action)();
}
} /* namespace NS_COMMAND */
ConcreteCommand
#include "Receiver.h"
namespace NS_COMMAND {
class ConcreteCommand {
public:
ConcreteCommand(Receiver *receiver) : _receiver(receiver) {}
virtual ~ConcreteCommand() {}
virtual void execute(void)
{
_receiver->action();
}
private:
Receiver *_receiver;
};
} /* namespace NS_COMMAND */
Receiver
#include <iostream>
namespace NS_COMMAND {
class Receiver {
public:
Receiver() {}
virtual ~Receiver() {}
void action(void)
{
std::cout << "Receiver Action." << std::endl;
}
};
} /* namespace NS_COMMAND */
main
#include "Command/Command.h"
#include "Command/Receiver.h"
#include "Command/ConcreteCommand.h"
using namespace NS_COMMAND;
int main(void)
{
Receiver r;
ConcreteCommand cc(&r);
cc.execute();
// 使用模板创建简单命令
SimpleCommand<Receiver> sc(&r, &Receiver::action);
sc.execute();
}
附加: