命令設計模式是選中一個操做與操做的參數,並將它們封裝成對象去執行,記錄等等,在下面的例子中,Command是操做,他的參數是Computer,他們被包裹在Switch中。 從另外一個角度來講,命令模式包括4個部分,Command,Receiver,invoker,clinet。在這個例子中,一個具體的Command有一個接收者對象和喚醒執行接收者的方法,Invoker可使用不一樣的具體Command,client決定哪一個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 history = new ArrayList(); 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); } } }