命令设计模式接受一个操作及其参数,并将它们包装在要执行,记录的对象中。在下面的示例中,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);
}
}
}