設計模式——命令模式(Command Pattern)

命令模式將“請求”封裝成對象,以便使用不同的請求、隊列或者日誌來參數化其他對象。命令模式也支持撤銷的操作。


類圖

173521625.png(圖片源於網絡)


代碼實現(Java)

// Command.java
public interface Command {
    public void execute();
}


// LightOffCommand.java
public class LightOffCommand implements Command {
    Light light;
                                
    public LightOffCommand(Light light) {
        this.light = light;
    }
                                
    public void execute() {
        light.off();
    }
}


// LightOnCommand.java
public class LightOnCommand implements Command {
    Light light;
                             
    public LightOnCommand(Light light) {
        this.light = light;
    }
                            
    public void execute() {
        light.on();
    }
}


// GarageDoorOpenCommand.java
public class GarageDoorOpenCommand implements Command {
    GarageDoor garageDoor;
    public GarageDoorOpenCommand(GarageDoor garageDoor) {
        this.garageDoor = garageDoor;
    }
    public void execute() {
        garageDoor.up();
    }
}


// Light.java
public class Light {
    public Light() {
    }
    public void on() {
        System.out.println("Light is on");
    }
    public void off() {
        System.out.println("Light is off");
    }
}


// GarageDoor.java
public class GarageDoor {
    public GarageDoor() {
    }
    public void up() {
        System.out.println("Garage Door is Open");
    }
    public void down() {
        System.out.println("Garage Door is Closed");
    }
    public void stop() {
        System.out.println("Garage Door is Stopped");
    }
    public void lightOn() {
        System.out.println("Garage light is on");
    }
    public void lightOff() {
        System.out.println("Garage light is off");
    }
}


// This is the invoker
// SimpleRemoteControl.java
public class SimpleRemoteControl {
    Command slot;
           
    public SimpleRemoteControl() {}
           
    public void setCommand(Command command) {
        slot = command;
    }
           
    public void buttonWasPressed() {
        slot.execute();
    }
}


測試代碼

// RemoteControlTest.java
public class RemoteControlTest {
    public static void main(String[] args) {
        SimpleRemoteControl remote = new SimpleRemoteControl();
        Light light = new Light();
        GarageDoor garageDoor = new GarageDoor();
        LightOnCommand lightOn = new LightOnCommand(light);
        GarageDoorOpenCommand garageOpen =
            new GarageDoorOpenCommand(garageDoor);
       
        remote.setCommand(lightOn);
        remote.buttonWasPressed();
        remote.setCommand(garageOpen);
        remote.buttonWasPressed();
    }
}


運行效果

174307495.png


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