[译]Java 设计模式之命令
(文章翻译自Java Design Pattern: Command)
命令设计模式在进行执行和记录的时候需要一个操作及其参数和封装在一个对象里面。在下面的例子中,命令是一个操作,它的参数是一个Computer,而且他们被封装在一个Switch中。
从另外一个视角来看,命令模式有四个部分:command,recevier,invoker和client。在这个例子中,Switch是invoker,Computer是receiver。一个具体的Command需要一个receiver对象而且调用receiver的方法。invok儿使用不同的具体Command。Client决定对于receiver去使用哪个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);
}
}
}