Skip to content

命令模式

意图

将一个请求封装为对象,从而可用不同请求参数化客户、排队、记录日志、支持撤销。

类图

Java 示例

java
public class Light {
    public void on() { System.out.println("light on"); }
    public void off() { System.out.println("light off"); }
}

public interface Command {
    void execute();
    void undo();
}

public class LightOnCommand implements Command {
    private final Light light;
    public LightOnCommand(Light l) { this.light = l; }
    public void execute() { light.on(); }
    public void undo() { light.off(); }
}

public class Remote {
    private Command slot;
    public void setCommand(Command c) { this.slot = c; }
    public void press() { slot.execute(); }
}

GUI 按钮绑定 Action、线程池提交 Runnable 均可视为命令。

下一节:解释器模式