設計模式系列(圖文解析,附帶原始碼) - 命令

Hi丶ImViper發表於2020-10-16

2. 命令(Command)

Intent

將命令封裝成物件中,具有以下作用:

  • 使用命令來引數化其它物件
  • 將命令放入佇列中進行排隊
  • 將命令的操作記錄到日誌中
  • 支援可撤銷的操作

Class Diagram

  • Command:命令
  • Receiver:命令接收者,也就是命令真正的執行者
  • Invoker:通過它來呼叫命令
  • Client:可以設定命令與命令的接收者
設計模式系列(圖文解析,附帶原始碼) - 命令

Implementation

設計一個遙控器,可以控制電燈開關。

設計模式系列(圖文解析,附帶原始碼) - 命令

public interface Command {
    void execute();
}
public class LightOnCommand implements Command {
    Light light;

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

    @Override
    public void execute() {
        light.on();
    }
}
public class LightOffCommand implements Command {
    Light light;

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

    @Override
    public void execute() {
        light.off();
    }
}
public class Light {

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

    public void off() {
        System.out.println("Light is off!");
    }
}
/**
 * 遙控器
 */
public class Invoker {
    private Command[] onCommands;
    private Command[] offCommands;
    private final int slotNum = 7;

    public Invoker() {
        this.onCommands = new Command[slotNum];
        this.offCommands = new Command[slotNum];
    }

    public void setOnCommand(Command command, int slot) {
        onCommands[slot] = command;
    }

    public void setOffCommand(Command command, int slot) {
        offCommands[slot] = command;
    }

    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
    }

    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
    }
}
public class Client {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Light light = new Light();
        Command lightOnCommand = new LightOnCommand(light);
        Command lightOffCommand = new LightOffCommand(light);
        invoker.setOnCommand(lightOnCommand, 0);
        invoker.setOffCommand(lightOffCommand, 0);
        invoker.onButtonWasPushed(0);
        invoker.offButtonWasPushed(0);
    }
}

JDK

相關文章