設計模式 -> 行為型 - 命令模式(Command)
阿新 • • 發佈:2022-05-17
命令模式(Command pattern): 將"請求"封閉成物件, 以便使用不同的請求,佇列或者日誌來引數化其他物件. 命令模式也支援可撤銷的操作。
1. 意圖
將命令封裝成物件中,以便使用命令來引數化其它物件,或者將命令物件放入佇列中進行排隊,或者將命令物件的操作記錄到日誌中,以及支援可撤銷的操作。
2. 類圖
Command: 命令
Receiver: 命令接收者,也就是命令真正的執行者
Invoker: 通過它來呼叫命令
Client: 可以設定命令與命令的接收者
3. 實現
設計一個遙控器,可以控制電燈開關。
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);
}
}