命令模式--Head First设计模式【笔记】

当客户好爽啊!因为他可以经常使用命令模式:列一堆需求清单,直接丢给工程师,工程师就知道该怎么实现那些需求!!

这篇文章是来介绍命令模式,首先我们来分析下上面这个场景。

1.客户这个对象他有好多的需求,好多的命令,而且这些命令是变化的。那么依据设计模式原则,我们就想用一个接口把这些命令封装起来。

2.清单里面有好多命令啊!清单实现接口,把客户的命令都封装到接口的方法中。

3.工程师接到清单,清单有好多种,但是所有清单都实现了接口的方法。调用接口的方法就能实现客户封装在清单接口中的所有命令。

文字描述好像有点不靠谱,那我们用代码说话吧:

    /// <summary>
    /// 客户--灯
    /// 它有好多命令,这里我们只列举了两个。
    /// </summary>
    class Light
    {
        public void  On() 
        {
            Console.WriteLine("The light is open.");
        }
        public void  Off() 
        {
            Console.WriteLine("The light is closed");
        }
        //其他方法
    }

 

 /// <summary>
    /// 命令接口
    /// 用来把客户的命令封装起来
    /// </summary>
    interface ICommand
    {
         void execute();
    }
 /// <summary>
    /// 清单
    /// 
    /// 实现命令接口,封装客户(灯)的命令。
    /// </summary>
    class LightOnCommand:ICommand 
    {
        Light light;
        public LightOnCommand(Light light) //需要通过构造函数传进来一个对象
        {
            this.light = light;
        }

        public void execute()//封装客户(灯)的命令。
        {
            light.On();

            //其他操作方法
        }

       
    }
 /// <summary>
    /// 工程师
    /// 
    /// setCommand 接受清单
    /// buttonWasPressed 执行清单
    /// </summary>
    class SimpleRemoteControl
    {
        ICommand slot;
        public SimpleRemoteControl() { }
        public void setCommand(ICommand command)//所有清单都实现ICommand接口
        {
            slot = command;
        }

        public void buttonWasPressed() //调用接口中封装命令的execute方法来执行客户的命令
        {
            slot.execute();
        }
    }

调试下,让三者关联起来:工程师开灯

            Light light = new Light();//客户
            LightOnCommand lightOnCommand = new LightOnCommand(light );//清单
            SimpleRemoteControl remote = new SimpleRemoteControl();//工程师
            remote.setCommand(lightOnCommand);//工程师接受清单
            remote.buttonWasPressed();//工程师执行清单中的客户命令

            Console.ReadKey();

显示结果:

(感觉看完模式的实现后,各种设计模式都蛮简单,重要的是那些设计模式的设计原则!!!!那些思想!!!)

posted on 2012-09-06 15:22  妖叨叨  阅读(766)  评论(1编辑  收藏  举报

导航