【24种设计模式】命令模式

动机:将一个请求封装成命令,解耦命令请求者与命令执行者之间的耦合。 


#include <iostream>
using namespace std;

//参与者 Invoker, Receiver, Command, ConcreteCommand

class Document
{
public:
	void Open() { cout<<"打开文档"<<endl; }
	void Close() { cout<<"关闭文档"<<endl; }
	void Paste() { cout<<"拷贝文字段"<<endl; }
	void Delete() { cout<<"删除文字段"<<endl; }
};

class Command
{
public:
	virtual ~Command() {}
	virtual void Execute() = 0;
};

// class PasteCommand : public Command
// {
// public:
// 	PasteCommand(Document* p);
// 	virtual ~PasteCommand();
// 
// 	virtual void Execute();
// 
// private:
// 	Document*		_document;
// };
// 
// class OpenCommand : public Command
// {
// public:
// 	OpenCommand(Document* p);
// 	virtual ~OpenCommand();
// 
// 	virtual void Execute();
// };

template<typename T>
class SimpleCommand : public Command
{
public:
	typedef void (T::*Action)();

	SimpleCommand(T* pT, Action a)
	{
		m_pT = pT;
		_action = a;
	}
	virtual ~SimpleCommand(){}

	virtual void Execute()
	{
		(m_pT->*_action)();
	}

private:
	T*		m_pT;
	Action  _action;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Document doc;

	SimpleCommand<Document> cmd1(&doc, &Document::Open);
	cmd1.Execute();

	SimpleCommand<Document> cmd2(&doc, &Document::Paste);
	cmd2.Execute();

	system("pause");
	return 0;
}


你可能感兴趣的:(【24种设计模式】命令模式)