Java设计模式:命令

命令设计模式接受一个操作及其参数,并将它们包装在要执行,记录的对象中。在下面的示例中,Command是一个操作,其参数是Computer,并包装在Switch中。

从另一个角度来看,命令模式包含4个部分:命令,接收者,调用者和客户端。在此示例中,Switch是调用者,而Computer是接收者。一个具体的Command有一个接收者对象,并调用接收者的方法。调用者可以使用其他具体命令。客户端确定要用于接收器的命令。
命令模式类图
在这里插入图片描述
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);
      }
   }
}

在这里插入图片描述

发布了17 篇原创文章 · 获赞 0 · 访问量 186

猜你喜欢

转载自blog.csdn.net/qq_41806546/article/details/105133812
今日推荐