命令模式-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;
}
// 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;
}
相关文章推荐
- C++--memset与sizeof
- c语言之date_format日期格式化和strptime函数windows平台上实现
- 提高项目13-成绩处理 函数版
- 程序编译出错记录及解决方案
- C++基础3 类:构造 拷贝 析构函数 静态变量函数 const初始化列表 new delete this 面向对象模型
- C++混合编程之idlcpp教程Python篇(8)
- c++ 模板的重载
- c语言之strreplace字符串替换
- 用C语言实现常见的三种中文内码转换
- C++编程规范---C++/C代码审查表
- C/C++编程新手错误语录
- c++类成员函数作为回调函数
- c语言学习笔记41
- C++实现字符串替换的两种方法
- C++接口定义及实现举例
- C++标准模板库
- 354. Russian Doll Envelopes(C++实现)
- C++ 类的继承三(继承中的构造与析构)
- C++编写线程池
- C++类的构造函数与析构函数