溫馨提示×

java命令模式如何實現

小樊
105
2024-11-25 00:48:29
欄目: 編程語言

在Java中,命令模式(Command Pattern)是一種行為設計模式,它允許你將一個請求封裝為一個對象,從而使你能夠使用不同的請求、隊列或日志請求參數化其他對象。此外,它還支持可撤銷的操作。

以下是如何在Java中實現命令模式的步驟:

  1. 創建一個命令接口(Command):
public interface Command {
    void execute();
}
  1. 為每個具體命令創建一個類,實現命令接口:
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();
    }
}

在這個例子中,我們有兩個具體命令:LightOnCommandLightOffCommand,它們分別實現了 Command 接口。這些類接收一個 Light 對象作為參數,并在 execute 方法中調用相應的 on()off() 方法。

  1. 創建一個接收者類(Receiver):
public class Light {
    public void on() {
        System.out.println("Light is ON");
    }

    public void off() {
        System.out.println("Light is OFF");
    }
}

在這個例子中,Light 類是接收者,它包含了 on()off() 方法。

  1. 創建一個調用者類(Invoker):
public class RemoteControl {
    Command command;

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

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

在這個例子中,RemoteControl 類是調用者,它包含一個 Command 接口類型的成員變量 command。setCommand 方法用于設置要執行的命令,而 pressButton 方法則調用該命令的 execute 方法。

  1. 使用命令模式:
public class Main {
    public static void main(String[] args) {
        Light light = new Light();
        Command lightOn = new LightOnCommand(light);
        Command lightOff = new LightOffCommand(light);

        RemoteControl remoteControl = new RemoteControl();

        remoteControl.setCommand(lightOn);
        remoteControl.pressButton(); // 輸出 "Light is ON"

        remoteControl.setCommand(lightOff);
        remoteControl.pressButton(); // 輸出 "Light is OFF"
    }
}

在這個例子中,我們首先創建了一個 Light 對象和兩個具體命令(lightOnlightOff)。然后,我們創建了一個 RemoteControl 對象,并使用 setCommand 方法設置要執行的命令。最后,我們調用 pressButton 方法來執行命令。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女