23种设计模式-java

command模式

2018-06-08  本文已影响3人  oneWeekOneTopic

解决问题

使发令者与执行者之间相分离。

应用场景

比如后台开发过程中的请求数据库、RPC接口等。通常情况下,我们会将请求逻辑(参数封装、结果解析、异常控制等)交给请求方控制,这样会导致代码逻辑十分混乱,业务逻辑与接口请求逻辑混杂在一起。

原理图

image

示例

这个的代码写得太多了,就不再举了,借用wikipedia的例子吧。

import java.util.List;
import java.util.ArrayList;

/** The Command interface */
public interface Command {
   void execute();
}

/** The Invoker class */
public class Switch {
   private List<Command> history = new ArrayList<Command>();

   public void storeAndExecute(final Command cmd) {
      this.history.add(cmd); // optional
      cmd.execute();
   }
}

/** The Receiver class */
public class Light {

   public void turnOn() {
      System.out.println("The light is on");
   }

   public void turnOff() {
      System.out.println("The light is off");
   }
}

/** The Command for turning on the light - ConcreteCommand #1 */
public class FlipUpCommand implements Command {
   private Light theLight;

   public FlipUpCommand(final Light light) {
      this.theLight = light;
   }

   @Override    // Command
   public void execute() {
      theLight.turnOn();
   }
}

/** The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
   private Light theLight;

   public FlipDownCommand(final Light light) {
      this.theLight = light;
   }

   @Override    // Command
   public void execute() {
      theLight.turnOff();
   }
}

/* The test class or client */
public class PressSwitch {
   public static void main(final String[] arguments){
      // Check number of arguments
      if (arguments.length != 1) {
         System.err.println("Argument \"ON\" or \"OFF\" is required.");
         System.exit(-1);
      }

      final Light lamp = new Light();
      
      final Command switchUp = new FlipUpCommand(lamp);
      final Command switchDown = new FlipDownCommand(lamp);

      final Switch mySwitch = new Switch();

      switch(arguments[0]) {
         case "ON":
            mySwitch.storeAndExecute(switchUp);
            break;
         case "OFF":
            mySwitch.storeAndExecute(switchDown);
            break;
         default:
            System.err.println("Argument \"ON\" or \"OFF\" is required.");
            System.exit(-1);
      }
   }
}

解释一下,Switch相当于是原理图Client,并没有使用Receiver

参考

https://en.wikipedia.org/wiki/Command_pattern

上一篇 下一篇

猜你喜欢

热点阅读