设计模式之命令模式

命令模式

      将请求封装成对象,以便使用不同的请求。队列或者日志来参数化其它对象。命令模式也支持可撤销的操作。

特点:

  1.命令模式将发出请求的对象和执行请求的对象解耦

  2.在被解耦的两者之间是通过命令对象进行沟通的。命令对象封装了接收者和一个或一组动作。

  3.调用者通过调用命令对象的执行方法发出请求,这会使接收者的动作被调用。

  4.调用者可以接受命令当作参数,甚至在运行时动态的进行。

具体代码直接拿设计模式的例子(摇控器开关的例子):

接口:

    public interface Commnad {

        public void execute();

    }

实现开关的类:

   public class LightOnCommnad implements Command {

       Light light;

       

       public LightOnCommnad(Light light) {

            this.light = light;

       }

       public void execute() {

            light.on();

       }

       class Light {

             public Light() {};

             public void on() {

                  System.out.println("Light is on!");

             }

       }

    }

命令对象:

   public class SimpleRemoteControl {

       Command slot;

       

       public SimpleRemoteControl() {}

       public void setCommand(Command command) {

            this.slot = command;

       }

   

       public void buttonWasPressed() {

           slot.execute();

       }

简单测试:

     public class RemoteControlTest {

         public static void main(String[] args) {

             SimpleRemoteControl remote = SimpleRemoteControl();

             Light light = new Light();

             LightOnCommand lightOn = new LightOnCommand(light);

             

             remote.setCommand(lightOn);

             remote.buttonWasPressed();

         }

      }

猜你喜欢

转载自washingtin.iteye.com/blog/2311078
今日推荐