一、UML图
二、介绍
命令模式(Command),将一个请求封装为一个对象,从而可使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。【DP】
命令模式经常与职责链模式(Chain of Responsibility)和组合模式(Composite)一起使用:职责链模式处理命令模式封装的对象,组合模式可以把简单的命令对象组合成复杂的命令对象。
三、代码示例
#include <iostream>
using namespace std;
class Receiver
{
public:
void action()
{
cout << "excute action" << endl;
}
};
class Command
{
public:
Command(Receiver *recv):receiver(recv){}
virtual void excute() = 0;
protected:
Receiver *receiver;
};
class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver *receiver):Command(receiver){}
virtual void excute()
{
receiver->action();
}
};
class Invoker
{
public:
void setCommand(Command *comm)
{
command = comm;
}
void excuteCommand()
{
command->excute();
}
private:
Command *command;
};
int main()
{
Receiver *recv = new Receiver();
Command *comm = new ConcreteCommand(recv);
Invoker *invo = new Invoker();
invo->setCommand(comm);
invo->excuteCommand();
delete recv;
delete comm;
delete invo;
getchar();
return 0;
}