阅读 255

command模式

解决问题

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

应用场景

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

原理图

  • Client:调用方

  • Receiver:这个可有可无,主要做回调。获取concreteCommand的执行结果,返回给客户端

  • ConcreteCommand:具体命令执行者

  • Command:抽象类或者接口(一般情况是抽象类,用于封装通用逻辑)

  • Caller:被调用的接口(一个或多个)

示例

这个的代码写得太多了,就不再举了,借用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