设计模式——命令模式_Command Pattern

命令模式:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations(将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能

Command 模式通过将请求封装到一个对象 (Command)中,并将请求的接受者存放到具体的ConcreteCommand 类中 (Receiver)中,从而实现调用操作的对象和操作的具体实现者之间的解耦。 


C++实现:

#ifndef __COMMAND_H__
#define __COMMAND_H__

#include 
using namespace std;

class Receiver {
public:
	void Action() { cout<<"Receiver Action..." << endl;}
};

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

class ConcreteCommand : public Command {
public:
	ConcreteCommand() { _pRec = new Receiver(); }
	ConcreteCommand(Receiver* pRec) : _pRec(pRec) { }
	virtual ~ConcreteCommand() { delete _pRec; }
	void Execute() {
		cout << "ConcreteCommand Execute: ";
		_pRec->Action();
	}
private:
	Receiver* _pRec;
};

class Invoker {
public:
	Invoker(Command* pCom) : _pCom(pCom) { }
	~Invoker() { delete _pCom; }
	void Invoke() { _pCom->Execute(); }
private:
	Command* _pCom;
};



#endif


#include "Command.h"


int main()
{
	//Receiver* pReceiver = new Receiver();
	Command* pCommand = new ConcreteCommand(/* pReceiver */);
	Invoker* pInvoker = new Invoker(pCommand);

	pInvoker->Invoke();

	delete pInvoker;
	return 0;
}


你可能感兴趣的:(Design,Pattern,command,设计模式,delete,class,action,object)