zoukankan      html  css  js  c++  java
  • 【设计模式】命令模式

    命令模式:将请求封装在对象中,客户不直接调用某个对象的方法,而是使用命令,将命令传递给拥有方法的对象从而让某一方法被调用。UML图例如以下:



    以下是用C++描写的命令模式的一个简单样例:

    #include <iostream>
    #include <string>
    #include <list>
    
    using namespace std;
    
    // Interface
    class Command {
    public:
    	virtual void Execute() = 0;
    };
    
    /* Invoker命令发送者 */
    class Switch {
    public:
    	// 存储命令
    	void Add(Command *command)
    	{
    		commands.push_back(command);
    	}
    
    	// 删除命令
    	void Remove(Command *command)
    	{
    		commands.remove(command);
    	}
    
    	// 运行全部命令的发送
    	void Execute()
    	{
    		list<Command*>::iterator iter = commands.begin();
    		for (; iter != commands.end(); ++iter)
    		{
    			(*iter)->Execute();
    		}
    	}
    
    private:
    	list<Command*> commands;
    };
    
    /* The Receiver class */
    class Light {
    public:
    	void TurnOn()
    	{
    		cout << "The light is on" << endl;
    	}
    
    	void TurnOff()
    	{
    		cout << "The light is off" << endl;
    	}
    };
    
    /* The Command for turning on the light - ConcreteCommand #1 */
    class FlipUpCommand : public Command {
    public:
    	FlipUpCommand(Light light)
    	{
    		light = light;
    	}
    
    	void Execute()
    	{
    		light.TurnOn();
    	}
    private:
    	Light light;	// 命令中包括命令接收者
    };
    
    /* The Command for turning off the light - ConcreteCommand #2 */
    class FlipDownCommand : public Command {
    public:
    	FlipDownCommand(Light light)
    	{
    		light = light;
    	}
    
    	void Execute()
    	{
    		light.TurnOff();
    	}
    private:
    	Light light;	// 命令中包括命令接收者
    };
    
    int main()
    {
    	Light light;	// 灯有‘开’、‘关’两种操作
    	Command *up = new FlipUpCommand(light);		// ‘开’命令
    	Command *down = new FlipDownCommand(light);	// ‘关’命令
    	Switch sw;
    
    	sw.Add(up);		// 命令交给开关
    	sw.Add(down);	// 命令交给开关
    	sw.Execute();	// 开关运行命令
    
    	sw.Remove(up);
    	sw.Execute();	// 开关运行命令
    
    
    	system("pause");
    	return 0;
    }

    执行结果:


    命令被封装成类,然后由某个Invoker(这里是switch开关类)保存、删除、发出命令。命令行的长处在于:把请求一个操作的对象(Invoker)与知道怎么运行一个操作的对象(Receiver)分隔开了。我们能够在实际操作開始之前或之后进行某些灵活的操作,比方:加入、删除、反复、记录日志等。


    參考:

    维基百科

    《大话设计模式》第23章

  • 相关阅读:
    在IIS中为SQL Server 2008配置报表服务
    安装VS2008 SP1
    SQL Server 2008正式发布了,示例数据库安装
    order by居然不能直接在union子句中使用
    如何让TabContainer居左
    公布下SQL Server 2008 RC0英文版下载地址
    BIT类型在SQL Server中的存储大小
    使用Windows照片库修改图片后记得清理原始图片副本
    老赵面试题参考答案(一)
    漂亮的系统后台UI 欣赏
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4083830.html
Copyright © 2011-2022 走看看