java命令模式

命令模式(Command Pattern):将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行參数化;对请求排队或者记录请求日志,以及支持可撤销的操作。

命令模式是一种对象行为型模式,其别名为动作(Action)模式或事务(Transaction)模式。

命令模式包括例如以下角色:

  • Command: 抽象命令类
  • ConcreteCommand: 详细命令类
  • Invoker: 调用者
  • Receiver: 接收者
  • Client:客户类


代码

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 Switch() {
   }

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

/* The Receiver class */
public class Light {
   public 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(Light light) {
      this.theLight = light;
   }

   public void execute(){
      theLight.turnOn();
   }
}

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

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

   public void execute() {
      theLight.turnOff();
   }
}

/* The test class or client */
public class PressSwitch {
   public static void main(String[] args){
      Light lamp = new Light();
      Command switchUp = new FlipUpCommand(lamp);
      Command switchDown = new FlipDownCommand(lamp);

      Switch mySwitch = new Switch();

      try {
         if ("ON".equalsIgnoreCase(args[0])) {
            mySwitch.storeAndExecute(switchUp);
         }
         else if ("OFF".equalsIgnoreCase(args[0])) {
            mySwitch.storeAndExecute(switchDown);
         }
         else {
            System.out.println("Argument "ON" or "OFF" is required.");
         }
      } catch (Exception e) {
         System.out.println("Arguments required.");
      }
   }
}

命令模式的长处

  • 减少系统的耦合度。
  • 新的命令能够非常easy地增加到系统中。
  • 能够比較easy地设计一个命令队列和宏命令(组合命令)。
  • 能够方便地实现对请求的Undo和Redo。

命令模式的缺点

  • 使用命令模式可能会导致某些系统有过多的详细命令类。由于针对每个命令都须要设计一个详细命令类,因此某些系统可能须要大量详细命令类,这将影响命令模式的使用。








原文地址:https://www.cnblogs.com/gccbuaa/p/7232742.html