行为型模式 - 命令模式 (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
    }
}
相关推荐
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤1 天前
工厂模式
设计模式
幂简集成explinks2 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java2 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h3 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa