c++ 设计模式--命令模式(20)

案例:小菜和大鸟去吃烧烤,向服务员点了烤羊肉串和烤鸡翅

命令模式

命令模式简介(CommandPattern)

将请求命令的发送者和命令的执行者完全解耦,每一个请求封装为一个对象,从而可以使用不同的请求对客户进行参数化,对请求排队和记录请求日志,以及支持可撤销的操作

命令模式结构

  • Command(抽象具体类): 声明用于执行命令的接口ExecuteCommand
  • ConcreteCommand(具体命令类): 实现执行命令的接口,由具体的接收者完成操作(将具体的请求封装为对象)
  • Invoker(调用者): 请求的发送者,聚合了具体的命令
  • Receiver(接收者): 实现处理请求的具体操作
    在这里插入图片描述

命令模式示例

https://gitee.com/NiMiKiss/design-pattern.git

#ifndef _COMMAND_PATTERN_
#define _COMMAND_PATTERN_
#include<iostream>
#include<vector>

class Barbecuer
{
public:
	void BakeMutton()
	{
		std::cout << "烤羊肉串" << std::endl;
	}
	void BakeChickening()
	{
		std::cout << "烤鸡翅" << std::endl;
	}
};

class Command
{
public:
	Command(std::shared_ptr<Barbecuer> spBarbecuer) :m_spBarbecuer(spBarbecuer) {}
	virtual void ExcuteCommand() = 0;
protected:
	std::shared_ptr<Barbecuer> m_spBarbecuer;
};

class BakeMuttonCommand :public Command
{
public:
	BakeMuttonCommand(std::shared_ptr<Barbecuer> spBarbecuer) :Command(spBarbecuer) {}
	void ExcuteCommand()
	{
		m_spBarbecuer->BakeMutton();
	}
};

class BakeChickenWingCommand :public Command
{
public:
	BakeChickenWingCommand(std::shared_ptr<Barbecuer> spBarbecuer) :Command(spBarbecuer) {}
	void ExcuteCommand()
	{
		m_spBarbecuer->BakeChickening();
	}
};

class Waiter
{
public:
	void SetOrder(std::shared_ptr<Command> spCommand)
	{
		std::cout << "增加订单" << std::endl;
		m_vecCommand.push_back(spCommand);
	}
	void CancelOrder(std::shared_ptr<Command> spCommand)
	{
		auto iteratorCommand = std::find(m_vecCommand.begin(), m_vecCommand.end(), spCommand);
		if (iteratorCommand != m_vecCommand.end())
		{
			m_vecCommand.erase(iteratorCommand);
			std::cout << "取消订单" << std::endl;
		}
	}
	void Notify()
	{
		for (size_t i = 0; i < m_vecCommand.size(); ++i)
		{
			m_vecCommand[i]->ExcuteCommand();
		}
	}
private:
	std::vector<std::shared_ptr<Command>> m_vecCommand;
};
#endif // !_COMMAND_PATTERN_

客户端调用

#include "Command_Pattern.h"
#include<iostream>
int main()
{
	auto spBarbecuer = std::shared_ptr<Barbecuer>(new Barbecuer());
	auto spBakeMuttonCommand = std::shared_ptr<BakeMuttonCommand>(new BakeMuttonCommand(spBarbecuer));
	auto spBakeChickenWingCommand = std::shared_ptr<BakeChickenWingCommand>(new BakeChickenWingCommand(spBarbecuer));

	auto spWaiter = std::shared_ptr<Waiter>(new Waiter());
	spWaiter->SetOrder(spBakeChickenWingCommand);
	spWaiter->SetOrder(spBakeMuttonCommand);
	spWaiter->Notify();
	return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值