//command 模式
class Command
{
public:
virtual ~Command(){}
virtual void Execute() = 0;
};
class Receiver
{
public:
void Action();
};
void Receiver::Action()
{
std::cout << "receiver action\n";
}
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver* pReceiver);
~ConcreteCommand();
virtual void Execute();
private:
Receiver* m_pReceiver;
};
ConcreteCommand::ConcreteCommand(Receiver* pReceiver)
:m_pReceiver(pReceiver)
{
}
ConcreteCommand::~ConcreteCommand()
{
SAFE_DELETE(m_pReceiver);
}
void ConcreteCommand::Execute()
{
if (NULL != m_pReceiver)
{
m_pReceiver->Action();
}
std::cout << "execute by concreteCommand\n";
}
class Invoke
{
public:
Invoke(Command* pCommand);
~Invoke();
void Call();
private:
Command* m_pCommand;
};
Invoke::Invoke(Command* pCommand)
:m_pCommand(pCommand)
{
}
Invoke::~Invoke()
{
SAFE_DELETE(m_pCommand);
}
void Invoke::Call()
{
if (NULL != m_pCommand)
{
m_pCommand->Execute();
}
}
int main()
{
/*
command模式
主要包括三个组件 receiver <---- command <--- invoker (指针调用 持有目标的指针)
command中保存有receiver的指针,这样command在execute的时候直接调用他的receiver执行就可以
invoker也保存有command的指针,这样 当我想要触发invoker的时候 invoker->call 就直接调用 它的command的execute就行了
这就是command模式
命令的出发和执行解耦合,我只需要执行触发,命令的执行会自动进行,因为命令的执行者包括在命令中 所以叫作命令模式
Receiver* r = new Receiver();
Command* c = new ConcreteCommand(r);
Invoke* i = new Invoke(c);
i->Call();
delete i;
*/
}