解释说明:命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传递给调用对象。调用对象寻找可以处理该命令的合适对象,并把该命令传给相应的对象,该对象执行命令。

命令抽象类(Command):定义命令的接口,声明执行的方法。
具体命令(ConcreteCommand):命令接口实现对象,是“虚”的实现;通常会持有接收者,并调用接收者的功能来完成命令要执行的操作。
实现者/接收者(Receiver):接收者,真正执行命令的对象。任何类都可能成为一个接收者,只要它能够实现命令要求实现的相应功能。
调用者/请求者(Invoker):要求命令对象执行请求,通常会持有命令对象,可以持有很多的命令对象。这个是客户端真正触发命令并要求命令执行相应操作的地方,也就是说相当于使用命令对象的入口。
- command.h
- #pragma once
- class Command
- {
- public:
- //每个命令类都必须有一个执行命令的方法
- virtual void execute() = 0;
- };
- receiver.h
- #pragma once
- class Receiver
- {
- public:
- //抽象接收者, 定义每个接收者都必须完成的业务
- virtual ~Receiver() { }
- virtual void doSomething() = 0;
- };
- concreteCommand.h
- #pragma once
- #include "command.h"
- #include "receiver.h"
- #include
- class ConcreteCommand1 :public Command
- {
- private:
- Receiver* m_pReceiver;//哪个Receiver类进行命令处理
- public:
- //构造函数传递接收者
- ConcreteCommand1(Receiver* receiver)
- {
- m_pReceiver = receiver;
- }
- //必须实现一个命令
- void execute()
- {
- //业务处理
- std::cout << "command1 run" << std::endl;
- m_pReceiver->doSomething();
- }
- };
- class ConcreteCommand2 : public Command
- {
- private:
- Receiver* m_pReceiver;
- public:
- ConcreteCommand2(Receiver* receiver)
- {
- m_pReceiver = receiver;
- }
- void execute()
- {
- std::cout << "command2 run" << std::endl;
- m_pReceiver->doSomething();
- }
- };
- concreteReciver.h
- #pragma once
- #include "receiver.h"
- #include
- class ConcreteReciver1 : public Receiver
- {
- //每个接收者都必须处理一定的业务逻辑
- public:
- void doSomething()
- {
- std::cout << "Reciver1 doing" << std::endl;
- }
- };
- class ConcreteReciver2 : public Receiver
- {
- //每个接收者都必须处理一定的业务逻辑
- public:
- void doSomething()
- {
- std::cout << "Reciver2 doing" << std::endl;
- }
- };
- invoker.h
- #pragma once
- #include "command.h"
- #include
- class Invoker
- {
- private:
- Command* m_pCommand;
- public:
- //接受命令
- void setCommand(Command* command)
- {
- m_pCommand = command;
- std::cout << "invoker add command" << std::endl;
- }
- //执行命令
- void action()
- {
- m_pCommand->execute();
- std::cout << "invoker action command" << std::endl;
- }
- };
- main.cpp
- #include "concreteCommand.h"
- #include "concreteReciver.h"
- #include "invoker.h"
- int main()
- {
- //首先声明调用者Invoker
- Invoker* invoker = new Invoker();
- //定义接收者
- Receiver* receiver = new ConcreteReciver1();
- Receiver* receiver2 = new ConcreteReciver2();
- //定义一个发送给接收者的命令
- Command* command = new ConcreteCommand1(receiver);
- Command* command2 = new ConcreteCommand2(receiver);
- Command* command3 = new ConcreteCommand1(receiver2);
- Command* command4 = new ConcreteCommand2(receiver2);
- //把命令交给调用者去执行
- invoker->setCommand(command);
- invoker->action();
- invoker->setCommand(command2);
- invoker->action();
- invoker->setCommand(command3);
- invoker->action();
- invoker->setCommand(command4);
- invoker->action();
- system("pause");
- return 0;
- }