先分析一个headfirst的简单case
命令
public interface Command {
public void execute();
}
受控制的实体:灯(接收者)
public class Light {
public Light() {
}
public void on() {
System.out.println("Light is on");
}
public void off() {
System.out.println("Light is off");
}
}
关灯命令,将命令作为对象
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.off();
}
}
invoker,调用者
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
}
测试代码
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
// GarageDoor garageDoor = new GarageDoor();
LightOffCommand lightOn = new LightOffCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}
命令模式的核心就是将命令作为对象,将接受者和调用者解耦。这里调用者不用理会接收者的细节,只管执行execute()方法就行。