命令接口本身只暴露excute
方法,不关心具体实现
public interface Command {
public void execute();
}
LightOnCommand
类实现Command
接口,excute
方法执行打开灯命令
public class LightOnCommand implements Command {
Light light;
public LightOnCommand (Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
SimpleRemoteControl
类有一个setCommand
方法负责设置命令,buttonWasPreesed
方法负责执行命令的excute
方法,具体excute
里面什么内容,没人关心
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();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}
网友评论