Clark To Do The blog of Clark

Java设计模式:命令模式

注:本文为译文,原文出处java-design-patterns-in-stories

命令设计模式获得一个操作及它的参数并将其封装在一个执行对象内, 记录日志等. 在下面的例子中, Command是一个操作, 它的参数是Computer, 它们被封装在Switch内.

另一方面, 命令模式包括四部分: 命令, 接收者, 触发器和客户端. 在这个例子内, Switch是触发器, Computer是接收者. 一个具体的Command持有一个接收者对象并且触发接收者的方法. 触发器可以使用不同的具体方法. 客户端绝对接收者使用哪个方法.

命令模式类图

command-design-pattern

命令模式Java样例

package designpatterns.command;

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

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

// in this example, suppose you use a switch to control computer

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

   public Switch() {
   }

   public void storeAndExecute(Command command) {
      this.history.add(command); // optional, can do the execute only!
      command.execute();
   }
}

/* The Receiver class */
 class Computer {

   public void shutDown() {
      System.out.println("computer is shut down");
   }

   public void restart() {
      System.out.println("computer is restarted");
   }
}

/* The Command for shutting down the computer*/
 class ShutDownCommand implements Command {
   private Computer computer;

   public ShutDownCommand(Computer computer) {
      this.computer = computer;
   }

   public void execute(){
      computer.shutDown();
   }
}

/* The Command for restarting the computer */
 class RestartCommand implements Command {
   private Computer computer;

   public RestartCommand(Computer computer) {
      this.computer = computer;
   }

   public void execute() {
      computer.restart();
   }
}

/* The client */
public class TestCommand {
   public static void main(String[] args){
      Computer computer = new Computer();
      Command shutdown = new ShutDownCommand(computer);
      Command restart = new RestartCommand(computer);

      Switch s = new Switch();

      String str = "shutdown"; //get value based on real situation

      if(str == "shutdown"){
          s.storeAndExecute(shutdown);
      }else{
          s.storeAndExecute(restart);
      }
   }
}
comments powered by Disqus