概念
将请求(命令)封装为对象,从而让可用不同的请求对客户进行参数化(将不同请求依赖注入到其他对象),并且能支持将请求放入队列或记录请求(命令)日志,以及支持可撤销的操作。
此模式允许请求方和接收方独立开来,使得请求方不必知道接收请方的接口,更不必知道请求如何被接收、操作是否被执行、何时被执行,以及是怎么被执行的。
代码示例
//命令接收者,接收命令并执行
class Receiver
{
public:
void driver() { qDebug() << "我开车了"; }
void cook() { qDebug() << "我做饭了"; }
};
//命令的抽象
class Command
{
public:
virtual ~Command() {}
virtual void execute() = 0; // 执行函数
};
//具体要执行操作的命令-开车
class ConcreteCommand_driver : public Command
{
public:
ConcreteCommand_driver(Receiver *receiver) : receiver(receiver){}
void execute() override
{
receiver->driver();
}
private:
Receiver *receiver;
};
//具体要执行操作的命令-开车
class ConcreteCommand_cook : public Command
{
public:
ConcreteCommand_cook(Receiver *receiver) : receiver(receiver){}
void execute() override
{
receiver->cook();
}
private:
Receiver *receiver;
};
//命令发送者
class Invoker
{
public:
Invoker() :command(nullptr) {}
bool setCommand(Command *command)
{
if(command)
{
this->command = command;
return true;
}
return false;
}
void executeCommand()
{
if (command)
{
command->execute();
}
}
private:
Command *command;
};
void doCommandPattern_driver()
{
Receiver *receiver = new Receiver();
Command *command = new ConcreteCommand_driver(receiver);
Invoker *invoker = new Invoker();
if (invoker->setCommand(command))
{
invoker->executeCommand();
}
else
{
qDebug() << "设置命令出错";
}
delete receiver;
delete command;
delete invoker;
}
void doCommandPattern_cook()
{
Receiver *receiver = new Receiver();
Command *command = new ConcreteCommand_cook(receiver);
Invoker *invoker = new Invoker();
if (invoker->setCommand(command))
{
invoker->executeCommand();
}
else
{
qDebug() << "设置命令出错";
}
delete receiver;
delete command;
delete invoker;
}
int main(int argc, char *argv[])
{
doCommandPattern_driver();//执行开车命令
qDebug()<<"------------------";
doCommandPattern_cook();//执行做饭命令
return 0;
}