panshiqu的专栏

给自己维护的项目打个广告:欢迎关注《休闲益智游戏》微信公众号

设计模式读书笔记:Command(命令)

意图:

将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。

结构图:来自 《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();
}
附加:
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/panshiqu/article/details/46833431
个人分类: 设计模式
上一篇设计模式读书笔记:Chain of Responsibility(责任链)
下一篇设计模式读书笔记:Interpreter(解释器)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭