//////////////////////////////////////////////////////////////////////////////////
// Command pattern
// - Encapsulate a request as an object, thereby letting you parameterize clients
// with different requests, queue or log requests, and support undoable operations.
//
// Author : ZAsia
// Date : 15/05/13
// Warning : In practice, declaration and implementation should
// be separated(.h and .cpp).
//////////////////////////////////////////////////////////////////////////////////
#include
using namespace std;
#define SAFE_DELETE_PTR(ptr) \
{ if (ptr) { delete ptr; ptr = nullptr; }}
// Receiver
// - knows how to perform the operations associated with carrying out a
// a request. Any class may serve as a Receiver.
class Receiver
{
public:
void Action()
{
cout << "Receiver::Action..." << endl;
}
};
// Command
// - declares an interface for executing an operation.
class Command
{
public:
virtual ~Command() { };
virtual void Execute() = 0;
};
// ConcreteCommand
// - defines a binding between a Receiver object and an action.
// - implements Execute by invoking the corresponding operations(s)
// on Receiver.
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver *receiver) : _receiver(receiver) { }
virtual void Execute()
{
_receiver->Action();
}
private:
Receiver *_receiver;
};
// Invoker
// - asks the command to carry out the request.
class Invoker
{
public:
Invoker(Command *command) : _command(command) { }
void Request()
{
_command->Execute();
}
private:
Command *_command;
};
// Client
// - creates a ConcreteCommand object and sets its receiver.
//
// Collaborations
// - The client creates a ConcreteCommand object and specifies its receiver.
// - An Invoker object stores the ConcreteCommand object.
// - The invoker issues a request by calling Execute on the command. When commands
// are undoable, ConcreteCommand stores state for undong the command prior to
// invoking Execute.
// - The ConcreteCommand object invokes operations on its receiver to carry out
// the request.
int main()
{
// creates a Receiver object
Receiver *pReceiverObj = new Receiver();
// creates a ConcreteCommand object and specifies its receiver
Command *pCommandObj = new ConcreteCommand(pReceiverObj);
// creates a Invoker object and stores the ConcreteCommand object
Invoker *pInvokerObj = new Invoker(pCommandObj);
// The invoker issues a request.
pInvokerObj->Request();
SAFE_DELETE_PTR(pReceiverObj);
SAFE_DELETE_PTR(pCommandObj);
SAFE_DELETE_PTR(pInvokerObj);
return 0;
}
///////////////////////////////////////////////////////////
// 1. Command decouples the object(Invoker) that invokes the operation form the
// one(Receiver) that knows how to perform it.
// 2. The object that issues a request only needs to know how to issue it; it
// doesn't need to know how the request will be carried out.
DesignPatterns_Command
最新推荐文章于 2021-12-29 22:15:08 发布