Java 设计模式之命令模式

本文深入探讨了设计模式中命令模式的应用,通过实例讲解如何将请求封装为对象,实现操作的参数化、队列化及日志记录。特别介绍了命令模式在支持可撤销操作上的优势,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文为笔者学习《Head First设计模式》的笔记,并加入笔者自己的理解和归纳总结

命令模式将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。

结构图
在这里插入图片描述
遥控器(RemoteControl)通过命令(Command)控制灯的开关(Light)。

public class RemoteControl {

    private Command command;

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

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

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

}

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

public class Light {

    public void turnOn() {
        System.out.println("light trun on");
    }

    public void turnOff() {
        System.out.println("light trun off");
    }
}

灯的开关命令

public class LightOnCommand implements Command {

    private Light light;

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

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

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

}

public class LightOffCommand implements Command {

    private Light light;

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

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

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

}

运行

public static void main(String[] args) {
    Light light = new Light();
    RemoteControl remoteControl = new RemoteControl();

    Command command = new LightOnCommand(light);
    remoteControl.setCommand(command);
    remoteControl.run();

    command = new LightOffCommand(light);
    remoteControl.setCommand(command);
    remoteControl.run();
    remoteControl.undo();
}

输出
在这里插入图片描述

相关文章
Java 设计模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值