大话设计模式--命令模式 Command -- C++实现实例

时间:2023-03-09 15:36:29
大话设计模式--命令模式 Command -- C++实现实例

1. 命令模式: 将请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。

大话设计模式--命令模式 Command -- C++实现实例

命令模式有点:

a. 较容易的设计一个命令队列

b. 在需要的的情况下,可以较容易的将命令加入日志

c. 允许请求的一方决定是否要否决请求。

d. 可以容易的实现对请求的撤销和重做。

e. 加入具体新的命令类不影响其他的类。

大话设计模式--命令模式 Command -- C++实现实例

实例:

receiver.h receiver.cpp  实际操作者  烤肉者

#ifndef RECEIVER_H
#define RECEIVER_H class Receiver
{
public:
Receiver();
void action();
}; #endif // RECEIVER_H
#include "receiver.h"
#include <stdio.h> Receiver::Receiver()
{
} void Receiver::action()
{
printf("Receiver action\n");
}

command.h command.cpp 命令抽象

#ifndef COMMAND_H
#define COMMAND_H #include "receiver.h" class Command
{
public:
Command(Receiver *receiver);
void virtual execute()=0; protected:
Receiver *receiver;
}; #endif // COMMAND_H
#include "command.h"

Command::Command(Receiver *receiver)
{
this->receiver = receiver;
}

concretecommand.h concretecommand.cpp 实际命名

#ifndef CONCRETECOMMAND_H
#define CONCRETECOMMAND_H #include "command.h" class ConcreteCommand : public Command
{
public:
ConcreteCommand(Receiver *receiver);
void execute();
}; #endif // CONCRETECOMMAND_H
#include "concretecommand.h"

ConcreteCommand::ConcreteCommand(Receiver *receiver) : Command(receiver)
{
} void ConcreteCommand::execute()
{
receiver->action();
}

invoker.h invoker.cpp

#ifndef INVOKER_H
#define INVOKER_H #include "command.h"
#include <QList> class Invoker
{
public:
Invoker();
void addCommand(Command *command);
void executeCommand(); private:
QList<Command*> *commandList;
}; #endif // INVOKER_H
#include "invoker.h"

Invoker::Invoker()
{
commandList = new QList<Command*>();
} void Invoker::addCommand(Command *command)
{
commandList->push_back(command);
} void Invoker::executeCommand()
{
for(int i=0; i!=commandList->count(); i++)
{
commandList->at(i)->execute();
}
}

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include "invoker.h"
#include "concretecommand.h" int main(int argc, char *argv[])
{
qDebug() << "Command test" ; Receiver *r = new Receiver();
Command *c1 = new ConcreteCommand(r);
Command *c2 = new ConcreteCommand(r);
Invoker *i = new Invoker();
i->addCommand(c1);
i->addCommand(c2);
i->executeCommand();
}