指令模式將操作封裝為獨立對象,與物件解耦,提升程式碼擴充性和重複使用性。在 Java 框架中,它常見於 MVC 架構、Servlet 過濾器、事務管理和訊息處理。實操範例展示如何使用 Java 實作指令模式,透過遙控器控制客廳和廚房燈的開關。
Java 框架中命令模式的應用場景
命令模式是一種設計模式,它允許你將操作封裝成單獨的對象。這使得你可以將操作與請求操作的物件解耦。這對於創建可擴展和可重複使用的程式碼非常有用。
在Java 框架中,指令模式用於各種場景,包括:
實戰案例
以下是使用 Java 實作指令模式的簡單範例:
interface Command { void execute(); } class LightOnCommand implements Command { private final Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOn(); } } class LightOffCommand implements Command { private final Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOff(); } } class Light { public void turnOn() { System.out.println("Light turned on."); } public void turnOff() { System.out.println("Light turned off."); } } class RemoteControl { private final Command[] onCommands; private final Command[] offCommands; public RemoteControl() { onCommands = new Command[7]; offCommands = new Command[7]; Command noCommand = new NoCommand(); for (int i = 0; i < 7; i++) { onCommands[i] = noCommand; offCommands[i] = noCommand; } } public void setCommand(int slot, Command onCommand, Command offCommand) { onCommands[slot] = onCommand; offCommands[slot] = offCommand; } public void onButtonWasPressed(int slot) { onCommands[slot].execute(); } public void offButtonWasPressed(int slot) { offCommands[slot].execute(); } private class NoCommand implements Command { @Override public void execute() {} } } public class CommandPatternDemo { public static void main(String[] args) { RemoteControl remoteControl = new RemoteControl(); Light livingRoomLight = new Light(); Light kitchenLight = new Light(); LightOnCommand livingRoomLightOnCommand = new LightOnCommand(livingRoomLight); LightOffCommand livingRoomLightOffCommand = new LightOffCommand(livingRoomLight); LightOnCommand kitchenLightOnCommand = new LightOnCommand(kitchenLight); LightOffCommand kitchenLightOffCommand = new LightOffCommand(kitchenLight); remoteControl.setCommand(0, livingRoomLightOnCommand, livingRoomLightOffCommand); remoteControl.setCommand(1, kitchenLightOnCommand, kitchenLightOffCommand); remoteControl.onButtonWasPressed(0); remoteControl.offButtonWasPressed(0); remoteControl.onButtonWasPressed(1); remoteControl.offButtonWasPressed(1); } }
以上是java框架中命令模式的應用場景有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!