行为型模式 - 命令模式 (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
    }
}
相关推荐
庞轩px12 小时前
第六篇:Spring用了哪些设计模式?——从单例到代理,拆解框架中的经典设计
java·spring·设计模式·bean·代理模式·aop·单例
多加点辣也没关系12 小时前
设计模式-工厂方法模式
设计模式·工厂方法模式
多加点辣也没关系16 小时前
设计模式-建造者模式
设计模式·建造者模式
多加点辣也没关系18 小时前
设计模式-桥接模式
设计模式·桥接模式
雪度娃娃19 小时前
结构型设计模式——装饰模式
设计模式·装饰器模式
sensen_kiss19 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.4 设计模式(下)
设计模式·软件工程
多加点辣也没关系20 小时前
设计模式-适配器模式
设计模式
基德爆肝c语言21 小时前
Qt:显示类控件
开发语言·qt·命令模式
Forget the Dream21 小时前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
Java面试题总结1 天前
【设计模式03】使用模版模式+责任链模式优化实战
设计模式·责任链模式