关闭

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

标签: 设计模式读书笔记Command命令
216人阅读 评论(0) 收藏 举报
分类:

意图:

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

结构图:来自 《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();
}
附加:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:86889次
    • 积分:1355
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:0篇
    • 译文:0篇
    • 评论:40条
    文章分类
    最新评论