您的位置:首页 > 编程语言 > C语言/C++

命令模式-c++实现

2016-06-29 23:51 411 查看
总感觉这些设计模式有些唬人。。。不过解耦上还是有很大帮助的

// CommandPattern.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

//烤肉师父
class RoastCooK
{
public:
void MakeMutton() { cout << "烤羊肉" << endl; }
void MakeChickenWing() { cout << "烤鸡翅膀" << endl; }

};

//抽象命令
class Command
{
protected:
RoastCooK * reciver;

public:
Command(RoastCooK *temp) :reciver(temp) {}
virtual void ExecuteCmd() = 0;
};

//烤肉命令
class MuttonCmd :public Command
{
public:
MuttonCmd(RoastCooK *temp):Command(temp){}
virtual void ExecuteCmd() { reciver->MakeMutton(); }
};

//烤鸡翅命令
class ChickenCmd: public Command
{
public:
ChickenCmd(RoastCooK *temp):Command(temp){}
virtual void ExecuteCmd() { reciver->MakeChickenWing(); }
};

//服务员类
class Waiter
{
protected:
vector<Command*> m_command;

public:
void SetCmd(Command* temp) { m_command.push_back(temp); }
void Notify()
{
vector<Command*>::iterator it;
for (it = m_command.begin(); it != m_command.end(); ++it)
{
(*it)->ExecuteCmd();
}
}
};

int main()
{
RoastCooK* cook = new RoastCooK();
Command *cmd1 = new MuttonCmd(cook);
Command *cmd2 = new ChickenCmd(cook);
Waiter *waiter = new Waiter();

//cmd
waiter->SetCmd(cmd1);
waiter->SetCmd(cmd2);

waiter->Notify();

//todo delete
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: