command模式

解决问题

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

应用场景

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

原理图

  • Client:调用方bash

  • Receiver:这个无关紧要,主要作回调。获取concreteCommand的执行结果,返回给客户端ide

  • ConcreteCommand:具体命令执行者ui

  • Command:抽象类或者接口(通常状况是抽象类,用于封装通用逻辑)this

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

示例

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

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,并无使用Receivercode

参考

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

相关文章
相关标签/搜索