命令设计模式是选中一个操做与操做的参数,并将它们封装成对象去执行,记录等等,在下面的例子中,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); } } }