参考博客
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define SAFE_DELETE(p) if (p) { delete p; p = NULL; }
/*下单页面*/
class Buy
{
public:
void buyvegetable() { cout << "下单了蔬菜" << endl; }
void buymeat() { cout << "下单了肉" << endl; }
void unbuyvegetable() { cout << "取消了蔬菜" << endl; }
void unbuymeat() { cout << "取消了肉" << endl; }
};
/*抽象命令类:是执行具体操作的接口*/
class Command
{
public:
Command() {}
Command(Buy *receiver) :p_receiver(receiver) {}
virtual void ExecuteCommand() = 0; //执行命令
virtual void UnCommand() = 0; //取消命令
protected:
Buy *p_receiver;
};
/*具体命令类:购买蔬菜*/
class BuyvegetableCommand :public Command
{
public:
BuyvegetableCommand(Buy* receiver) { p_receiver = receiver; }
void ExecuteCommand() { p_receiver->buyvegetable(); }
void UnCommand() { p_receiver->unbuyvegetable(); }
};
/*具体命令类:买肉命令*/
class BuymeatCommand :public Command
{
public:
BuymeatCommand(Buy*receiver) { p_receiver = receiver; }
void ExecuteCommand() { p_receiver->buymeat(); }
void UnCommand() { p_receiver->unbuymeat(); }
};
/*点菜页面*/
class Order
{
public:
void SetOrder(Command *command);
void UnOrder();
void Notify();
private:
vector<Command *>p_commandList; //这里相当于一个命令对象队列
};
void Order::SetOrder(Command *command) {
p_commandList.push_back(command);
cout << "增加菜单命令" << endl;
}
void Order::UnOrder() {
p_commandList.pop_back();
cout << "取消菜单命令" << endl;
}
void Order::Notify() {
vector<Command*>::iterator i;
for (i = p_commandList.begin(); i != p_commandList.end(); ++i)
(*i)->ExecuteCommand();
}
int main(int argc, char *argv[])
{
//生成购菜、点菜、订单对象
Buy *p_buy = new Buy();
Command *p_vegetable = new BuyvegetableCommand(p_buy);
Command *p_meat = new BuymeatCommand(p_buy);
Order *p_order = new Order();
//将订单对象推送到命令队列
p_order->SetOrder(p_vegetable);
p_order->SetOrder(p_meat);
p_order->UnOrder();
//点菜页面信息提交给购菜页面
p_order->Notify();
SAFE_DELETE(p_buy);
SAFE_DELETE(p_vegetable);
SAFE_DELETE(p_meat);
SAFE_DELETE(p_order);
return 0;
}