命令模式

Demo場景:通過遙控器控制Light開的動作。
核心是把方法封裝成對象

(1)遙控器類,能夠插入執行方法具體實現,並且按下按鈕發出執行具體方法的動作:SimpleRemoteControl類,Command爲插入指定方法的接口。

package designpattern.command.remotecontrol;

public class SimpleRemoteControl {

    Command slot;

    public SimpleRemoteControl(){}

    public void setCommand(Command command){
        slot = command;
    }

    public void buttonWasPressed(){
        slot.execute();
    }
}

(2)一般插入遙控板的執行方法都應該實現統一的接口,現在定義這個接口:Command, 包含執行方法的命令

package designpattern.command.remotecontrol;

public interface Command {

    public void execute();
}

(3)前面定義的只是執行方法的接口,需要一個具體實現的方法,但是這個方法是有具體的對象來執行的,因此先定義一個執行方法的具體類:Light

package designpattern.command.remotecontrol;

public class Light {

    public void on(){
        System.out.println("Light is on");
    }
}

(4)好了,有了執行具體方法的類了,那麼我們接着把這個類的方法封裝成一個遙控板執行的方法對象,這樣就成將這個執行方法具體實現插到遙控板上:LightOnCommand

package designpattern.command.remotecontrol;

public class LightOnCommand implements Command {

    Light light;

    public LightOnCommand(Light light){
        this.light = light;
    }
    @Override
    public void execute() {
        light.on();
    }

}

最後,演示一下用遙控器打開Light:

package designpattern.command.remotecontrol;

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();
    }

}
發佈了44 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章