行为型模式 - 命令模式 (Command Pattern)

行为型模式 - 命令模式 (Command Pattern)

命令模式将请求封装成一个对象,从而允许你使用不同的请求、队列或日志来参数化其他对象,同时支持请求的撤销与恢复。以下是几个常见的命令模式经典案例。


java 复制代码
// 1. 定义命令接口
interface Command {
    void execute();
    void undo();
}

// 2. 创建具体命令类
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.on();
    }

    @Override
    public void undo() {
        light.off();
    }
}

class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    @Override
    public void execute() {
        light.off();
    }

    @Override
    public void undo() {
        light.on();
    }
}

// 3. 创建接收者类
class Light {
    public void on() {
        System.out.println("Light is on");
    }

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

// 4. 创建调用者类
class RemoteControl {
    private Command command;

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

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

    public void pressUndo() {
        command.undo();
    }
}

// 5. 客户端代码
public class CommandPatternDemo {
    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();  // 输出: Light is on

        remote.setCommand(lightOff);
        remote.pressButton();  // 输出: Light is off

        // 撤销操作
        remote.pressUndo();     // 输出: Light is on
    }
}
相关推荐
林浩杨_4 小时前
linux搜索命令(grep+sed)
linux·命令模式
做前端的娜娜子13 小时前
从 0 到 1 打造一个配置可视化后台:一次前端配置中心化改造的实战复盘
前端·设计模式·数据可视化
执明wa18 小时前
Android 开发中的设计模式入门:六大设计原则
android·设计模式
莫得感情 o18 小时前
设计模式 09 · 适配器模式
设计模式·适配器模式
梅头脑1 天前
学了6种设计模式却写出了同事看不懂的代码——SOLID五原则反例对照,治好了我的"过度设计"
设计模式
workflower2 天前
案例:大模型驱动的“发现- 研判- 整改- 验证”全闭环治理体系
人工智能·深度学习·机器学习·设计模式·机器人
董员外2 天前
RAG 系统进化论(九):RAG 评测,怎样证明系统真的变好了?
人工智能·设计模式·程序员
西安小哥2 天前
AI时代技术工程师的"道法术器势":学习图谱、成长规划与角色重塑
人工智能·设计模式·程序员
莫得感情 o2 天前
设计模式 08 · 装饰器模式
设计模式·装饰器模式
董员外2 天前
RAG 系统进化论(八):Agentic RAG(智能体式 RAG),从回答问题到完成任务
人工智能·后端·设计模式