命令模式

命令接口本身只暴露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();
    }
}

你可能感兴趣的:(命令模式)