1. 程式人生 > >Java 設計模式之命令模式

Java 設計模式之命令模式

本文為筆者學習《Head First設計模式》的筆記,並加入筆者自己的理解和歸納總結

命令模式將“請求”封裝成物件,以便使用不同的請求、佇列或者日誌來引數化其他物件。命令模式也支援可撤銷的操作。

結構圖
在這裡插入圖片描述
遙控器(RemoteControl)通過命令(Command)控制燈的開關(Light)。

public class RemoteControl {

    private Command command;

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

    public void run() {
        command.execute();
    }

    public void undo() {
        command.undo();
    }

}

public interface Command {
    void execute();
    void undo();
}

public class Light {

    public void turnOn() {
        System.out.println("light trun on");
    }

    public void turnOff() {
        System.out.println("light trun off");
    }
}

燈的開關命令

public class LightOnCommand implements Command {

    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOn();
    }

    @Override
    public void undo() {
        light.turnOff();
    }

}

public class LightOffCommand implements Command {

    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.turnOff();
    }

    @Override
    public void undo() {
        light.turnOn();
    }

}

執行

public static void main(String[] args) {
    Light light = new Light();
    RemoteControl remoteControl = new RemoteControl();

    Command command = new LightOnCommand(light);
    remoteControl.setCommand(command);
    remoteControl.run();

    command = new LightOffCommand(light);
    remoteControl.setCommand(command);
    remoteControl.run();
    remoteControl.undo();
}

輸出

light trun on
light trun off
light trun on