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

#include <iostream>
#include <list>
using namespace std;

// Receiver类,知道如何实施与执行一个与请求相关的操作:
class Receiver {
public:
	void Action() {
		cout << "Receiver" << endl;
	}
};

// Command类,用来声明执行操作的接口
class Command {
public:
	virtual void Excute() = 0;
	virtual void setReceiver(Receiver* r) = 0;
	virtual ~Command() {};
};

// ConcreteCommand类,绑定一个Receiver,调用其相应操作以实现Excute:
class ConcreteCommand : public Command {
private:
	Receiver* receiver;
public:
	void setReceiver(Receiver* r) {
		receiver = r;
	}
	void Excute() {
		//cout << "ConcreteCommand" << endl;
		receiver->Action();
	}
};

// 要求该命令执行这个请求:
class Invoker {
private:
	list<Command* > commands;
public:
	void setCommand(Command* c) {
		commands.push_back(c);
	}
	void Notify() {
		for (auto c = commands.begin(); c != commands.end(); c++) {
			(*c)->Excute();
		}
	}
};

// 客户端实现代码:
int main() {
	Command* c = new ConcreteCommand();
	Receiver* r = new Receiver();
	c->setReceiver(r);

	Invoker i;
	i.setCommand(c);
	i.Notify();   // Receiver

	delete r;
	delete c;

	getchar();
	return 0;
}

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐