案例:小菜和大鸟去吃烧烤,向服务员点了烤羊肉串和烤鸡翅
命令模式
命令模式简介(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;
}