命令模式给我的感觉有点像观察者模式
网上找的原理图
Barbecuer.h
#ifndef BARBECUER_H_
#define BARBECUER_H_
#include<iostream>
using namespace std;
/**
* 烤肉串类
* 包括实现的功能
*/
class Barbecuer{
public:
// 烤羊肉
void bakeMutton(){
cout << "烤羊肉串咯!!!" << endl;
}
// 烤鸡翅
void bakeChickenWing(){
cout << "烤鸡翅咯!!!" << endl;
}
};
#endif
Command.h
#ifndef COMMAND_H_
#define COMMAND_H_
#include<iostream>
using namespace std;
#include "Barbecuer.h"
/**
* 命令抽象类
*/
class Command{
protected:
Barbecuer* receiver;
public:
Command(Barbecuer* receiver){
this->receiver = receiver;
}
// 执行命令
virtual void excuteCommand() = 0;
};
/**
* 烤羊肉串类
*/
class BakeMuttonCommand:public Command{
public:
BakeMuttonCommand(Barbecuer* receiver):Command(receiver){}
virtual void excuteCommand(){
receiver->bakeMutton();
}
};
/**
* 烤鸡翅类
*/
class BakeChickCommand : public Command{
public:
BakeChickCommand(Barbecuer* receiver):Command(receiver){}
virtual void excuteCommand(){
receiver->bakeChickenWing();
}
};
#endif
Waiter.h
#ifndef WAITER_H_
#define WAITER_H_
#include<iostream>
using namespace std;
#include<vector>
#include "Command.h"
class Waiter{
private:
vector<Command*> orders;
public:
// 设置订单
void addOrder(Command* cmd){
orders.push_back(cmd);
//其余操作.....
}
// 取消订单
void cancelOrder(Command* cmd){
// 取消操作
}
// 通知全部执行
void notify(){
for(Command* order : orders){
order->excuteCommand();
}
}
};
#endif
main.cpp
#include<iostream>
using namespace std;
#include "Waiter.h"
int main(){
// 开店前准备
Barbecuer *barbecuer = new Barbecuer; // 烧烤师傅
Command* bakeChickCommand = new BakeChickCommand(barbecuer); // 烤鸡翅
Command* bakeMuttonCommand = new BakeMuttonCommand(barbecuer); // 烤羊肉
Waiter *waiter = new Waiter; // 服务员
// 顾客点餐
waiter->addOrder(bakeChickCommand);
waiter->addOrder(bakeMuttonCommand);
// 点餐完毕,通知后厨
waiter->notify();
return 0;
}
书籍推荐:《大话设计模式》