Java命令模式,一個簡單示例

public interface Command {
    void exe();
}

 

public class Light {
    public void on(){
        System.out.println("打開");
    }
}

 

public class LightCommand implements Command {
    private Light light;

    public LightCommand(Light l) {
        this.light = l;
    }

    @Override
    public void exe() {
        light.on();
    }
}

 

 

public class RemoteControl {
    private Command command;

    public void setCommand(Command c) {
        this.command = c;
    }

    public void pressButton() {
        command.exe();
    }
}

 

public abstract class Main {
    public static void main(String[] args) {
        Light light = new Light();
        Command command = new LightCommand(light);

        RemoteControl remoteControl = new RemoteControl();
        remoteControl.setCommand(command);
        remoteControl.pressButton();
    }
}

 

輸出:

打開

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章