命令接口本身只暴露excute
方法抓于,不關心具體實現
public interface Command {
public void execute();
}
LightOnCommand
類實現Command
接口尽爆,excute
方法執(zhí)行打開燈命令
public class LightOnCommand implements Command {
Light light;
public LightOnCommand (Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
SimpleRemoteControl
類有一個setCommand
方法負責設置命令,buttonWasPreesed
方法負責執(zhí)行命令的excute
方法螟够,具體excute
里面什么內容灾梦,沒人關心
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl () {};
public void setCommand (Command command) {
slot = command;
}
public void buttonWasPressed () {
slot.execute();
}
}
測試執(zhí)行效果
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}