设计模式-命令模式
来源:互联网 发布:工程软件开发技术 编辑:程序博客网 时间:2024/04/29 13:56
1. 命令模式的角色组成
1) 命令角色(Command):生命执行操作的接口。接口或抽象类来实现。
2) 具体命令角色(Concrete Command):将一个接收者对象绑定于一个动作;调用接收者相应的操作,以实现命令角色声明的执行操作的接口。
3) 客户角色(Client): 创建一个具体命令对象(并可以设定它的接收者)。
4) 请求者角色(Invoker):调用命令对象执行这个请求。
5) 接收者角色(Receiver):知道如何实施与执行一个请求相关的操作。任何类都可能作为一个接收者。
命令模式类图:
暂缺
2. 应用实例
(本人感觉这个例子比较能切合类图的含义)
场景:某日,我去饭店吃饭,进去后对服务员说:“我要一个三明治”,服务员对厨师喊,“三明治一份”,我然后又说:“再来个煮鸡蛋。”服务员对厨师喊,“煮鸡蛋一份”,我说:“没了,就这些”,服务员喊,“就这些了,开做。”于是厨师开始做。
- #include "stdafx.h"
- #include <algorithm>
- #include <map>
- #include <iostream>
- using namespace std;
- //ICommand相当于服务员喊话的标准
- class ICommand
- {
- public:
- virtual void Execute()
- {
- };
- };
- //Receiver 相当于厨师
- class Receiver
- {
- //做鸡蛋
- public:
- void CookEgg()
- {
- cout << "Cooking an egg./n";
- }
- //做三明治
- void CookSandwich()
- {
- cout << "Cooking a sandwich./n";
- }
- };
- //喊话内容:鸡蛋
- class CookEggCommand : public ICommand
- {
- protected:
- Receiver* receiver;
- public:
- CookEggCommand(Receiver* receiver)
- {
- this->receiver = receiver;
- }
- void Execute()
- {
- receiver->CookEgg();
- }
- };
- //喊话内容:三明治
- class CookSandwichCommand : public ICommand
- {
- protected:
- Receiver* receiver;
- public:
- CookSandwichCommand(Receiver* receiver)
- {
- this->receiver = receiver;
- }
- void Execute()
- {
- receiver->CookSandwich();
- }
- };
- //Invoker 相当于服务员
- class Invoker
- {
- public:
- int iCount;
- map<int, ICommand*> commands;
- Invoker()
- {
- iCount = 0;
- }
- //喊话
- void SetCommand(ICommand* command)
- {
- commands.insert(map<int, ICommand*>::value_type(iCount, command));
- iCount++;
- }
- //执行喊话内容
- void ExecuteCommand()
- {
- int i;
- ICommand* cmd;
- for(i = 0; i < iCount; i++)
- {
- cmd = commands[i];
- cmd->Execute();
- }
- }
- };
- int main()
- {
- Receiver receiver;
- ICommand* egg= new CookEggCommand(&receiver);
- ICommand* sandwich = new CookSandwichCommand(&receiver);
- Invoker invoker;
- //服务员喊话,三明治一份
- invoker.SetCommand(sandwich);
- //服务员喊话,鸡蛋一份
- invoker.SetCommand(egg);
- //服务员喊话,没有别的了,做吧。
- invoker.ExecuteCommand();
- delete egg;
- delete sandwich;
- return 1;
- }
- 设计模式---命令模式
- 设计模式-命令模式
- 设计模式:命令模式
- 设计模式:命令模式
- 设计模式:命令模式
- 设计模式 命令模式
- 设计模式--命令模式
- 设计模式---命令模式
- 设计模式- 命令模式
- 设计模式---命令模式
- 设计模式 - 命令模式
- 【设计模式】【命令模式】
- 设计模式---命令模式
- 设计模式 - 命令模式
- 设计模式:命令模式
- 设计模式 - 命令模式
- 设计模式-命令模式
- 设计模式---命令模式
- ubuntu 8.0.4下面的tar和gzip
- SSH方式远程控制 ubuntu
- SERVICE_BOOT_START 驱动程序逆向
- ubuntu 为用户分配磁盘空间
- Ubuntu 8.0.4简单网络配置
- 设计模式-命令模式
- 打败你的十五个坏习惯
- transient与序列化
- sdf
- MySQL优化步骤及my.cnf缓存优化
- MySQL的维护语句
- void main(void) - 错误的用法
- ASP.NET如何存取SQL Server数据库图片
- javascript 学习