命令模式
定义:将一个请求封装为一个对象,从而可用不同的请求对客户进行参数化,对请求排队或者记录请求日志,以及支持可撤销的操作。
场景栗子:通信兵接收到司令官的命令,将这些命令发送给作战部队。
代码
#include<iostream>
#include <list>
using namespace std;
class Signalman;
class Action;
class Command
{
public:
Command(Action *action)
{
m_action = action;
}
virtual void ExecuteOrder() = 0;//执行命令
protected:
Action *m_action;
};
//行动
class Action
{
public:
void attack(string name)
{
cout << "进攻高地" << name.c_str() << endl;
}
void retreat()
{
cout << "所有队伍撤退" << endl;
}
private:
};
class AttackCommand :public Command
{
public:
AttackCommand(Action *act,string name) :Command(act){
m_name = name;
}
void ExecuteOrder(){
m_action->attack(m_name);
}
private:
string m_name;
};
class RetreatCommand :public Command
{
public:
RetreatCommand(Action *act) :Command(act){}
void ExecuteOrder(){
m_action->retreat();
}
};
//通信兵
class Signalman
{
public:
//通知军队
void noticeArmy()
{
for (Command*c : m_commandList)
{
c->ExecuteOrder();
}
}
//设置命令
void setCommand(Command* command)
{
m_commandList.push_back(command);
}
//取消命令
void cancelCommand(Command* command)
{
m_commandList.remove(command);
}
private:
list<Command*> m_commandList;
};
//客户端
int main()
{
Action *act = new Action;
Command *attack1 = new AttackCommand(act,"333");
Command *attack2 = new AttackCommand(act, "298");
Command *retreat = new RetreatCommand(act);
Signalman *man = new Signalman;
man->setCommand(attack1);
man->setCommand(attack2);
//下发进攻命令
man->noticeArmy();
cout << "----------久攻不下,损失惨重--------------" << endl;
man->cancelCommand(attack1);
man->cancelCommand(attack2);
man->setCommand(retreat);
//下发撤退命令
man->noticeArmy();
if (act){
delete act;
act = nullptr;
}
if (man){
delete man;
man = nullptr;
}
if (attack1){
delete attack1;
attack1 = nullptr;
}
if (attack2){
delete attack2;
attack2 = nullptr;
}
if (retreat){
delete retreat;
retreat = nullptr;
}
return 0;
}
效果: