设计模式command

spicy-food / 2024-08-28 / 原文

命令(Command)设计模式是一种行为型设计模式,它将请求封装为对象,从而使你可以将请求的发起者和请求的接收者解耦。这样,你可以使用不同的请求、队列或日志来管理请求,还可以支持可撤销的操作。

以下是一个简单的命令模式的例子:

假设我们有一个简单的遥控器,它可以控制灯的开和关。我们将定义一些命令对象来表示这些操作:

  1. 命令接口

    java
    public interface Command { void execute(); }
  2. 具体命令实现

    java
    public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOn(); } } public class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.turnOff(); } }
  3. 接收者

    java
    public class Light { public void turnOn() { System.out.println("Light is ON"); } public void turnOff() { System.out.println("Light is OFF"); } }
  4. 请求发起者(遥控器)

    java
    public class RemoteControl { private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } }
  5. 客户端代码

    java
    public class Client { public static void main(String[] args) { Light light = new Light(); Command lightOn = new LightOnCommand(light); Command lightOff = new LightOffCommand(light); RemoteControl remote = new RemoteControl(); remote.setCommand(lightOn); remote.pressButton(); // Output: Light is ON remote.setCommand(lightOff); remote.pressButton(); // Output: Light is OFF } }

在这个示例中:

  • Command 是一个命令接口,定义了 execute 方法。
  • LightOnCommandLightOffCommand 是具体的命令实现,分别封装了打开和关闭灯的操作。
  • Light 是接收者,实际执行操作的对象。
  • RemoteControl 是请求发起者,它持有一个 Command 对象并在按钮按下时调用 execute 方法。

这样,遥控器(请求发起者)不需要知道具体的操作细节,只需要调用 execute 方法,这些操作的具体实现都封装在命令对象里。这使得代码更加灵活和可扩展。