命令模式將“請求”封裝成對象,以便使用不同的請求、隊列或者日誌來參數化其他對象。命令模式也支持撤銷的操作。
類圖
代碼實現(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(); } }
運行效果