当前位置: 首页 > news >正文

Java命令模式详解

命令模式详解

一、命令模式概述

命令模式(Command Pattern)是一种行为型设计模式,它将请求封装为对象,从而允许使用不同的请求参数化其他对象,并支持请求的排队、记录、撤销等操作。

核心特点

  • 解耦调用者与执行者:调用者无需知道具体执行细节
  • 参数化请求:可将命令对象作为参数传递
  • 支持撤销/重做:记录命令历史实现操作回滚
  • 支持事务:实现命令的原子执行

二、命令模式的结构

主要角色

  1. Command:抽象命令接口
  2. ConcreteCommand:具体命令实现
  3. Invoker:调用者/请求者
  4. Receiver:命令接收者/执行者
  5. Client:创建具体命令并设置接收者

三、命令模式的实现

1. 基本实现

// 命令接口
public interface Command {
    void execute();
    void undo();
}

// 接收者 - 知道如何执行操作
public class Light {
    public void on() {
        System.out.println("开灯");
    }
    
    public void off() {
        System.out.println("关灯");
    }
}

// 具体命令 - 开灯命令
public class LightOnCommand implements Command {
    private Light light;
    
    public LightOnCommand(Light light) {
        this.light = light;
    }
    
    public void execute() {
        light.on();
    }
    
    public void undo() {
        light.off();
    }
}

// 调用者 - 遥控器
public class RemoteControl {
    private Command command;
    
    public void setCommand(Command command) {
        this.command = command;
    }
    
    public void pressButton() {
        command.execute();
    }
    
    public void pressUndo() {
        command.undo();
    }
}

// 使用示例
Light light = new Light();
Command lightOn = new LightOnCommand(light);

RemoteControl remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton();  // 开灯
remote.pressUndo();    // 关灯

2. 支持多命令和撤销历史

// 高级遥控器
public class AdvancedRemoteControl {
    private List<Command> commandHistory = new ArrayList<>();
    
    public void executeCommand(Command command) {
        command.execute();
        commandHistory.add(command);
    }
    
    public void undoLastCommand() {
        if (!commandHistory.isEmpty()) {
            Command lastCommand = commandHistory.remove(commandHistory.size() - 1);
            lastCommand.undo();
        }
    }
}

四、命令模式的应用场景

1. 文本编辑器操作

// 文档类 - 接收者
public class Document {
    private StringBuilder content = new StringBuilder();
    
    public void write(String text) {
        content.append(text);
    }
    
    public void delete(int length) {
        if (content.length() >= length) {
            content.delete(content.length() - length, content.length());
        }
    }
    
    public String getContent() {
        return content.toString();
    }
}

// 抽象命令
public interface TextCommand {
    void execute();
    void undo();
}

// 写入命令
public class WriteCommand implements TextCommand {
    private Document document;
    private String text;
    
    public WriteCommand(Document document, String text) {
        this.document = document;
        this.text = text;
    }
    
    public void execute() {
        document.write(text);
    }
    
    public void undo() {
        document.delete(text.length());
    }
}

// 编辑器 - 调用者
public class TextEditor {
    private List<TextCommand> history = new ArrayList<>();
    private Document document = new Document();
    
    public void executeCommand(TextCommand command) {
        command.execute();
        history.add(command);
    }
    
    public void undo() {
        if (!history.isEmpty()) {
            TextCommand lastCommand = history.remove(history.size() - 1);
            lastCommand.undo();
        }
    }
    
    public void showDocument() {
        System.out.println("当前文档内容: " + document.getContent());
    }
}

2. 交易系统

// 交易接收者
public class StockTrade {
    public void buy(String stock, int shares) {
        System.out.println("买入 " + shares + " 股 " + stock);
    }
    
    public void sell(String stock, int shares) {
        System.out.println("卖出 " + shares + " 股 " + stock);
    }
}

// 订单命令接口
public interface Order {
    void execute();
}

// 买入命令
public class BuyOrder implements Order {
    private StockTrade stockTrade;
    private String stock;
    private int shares;
    
    public BuyOrder(StockTrade stockTrade, String stock, int shares) {
        this.stockTrade = stockTrade;
        this.stock = stock;
        this.shares = shares;
    }
    
    public void execute() {
        stockTrade.buy(stock, shares);
    }
}

// 订单处理器 - 调用者
public class OrderProcessor {
    private List<Order> orders = new ArrayList<>();
    
    public void takeOrder(Order order) {
        orders.add(order);
    }
    
    public void processOrders() {
        for (Order order : orders) {
            order.execute();
        }
        orders.clear();
    }
}

3. 智能家居控制

// 设备接口
public interface SmartDevice {
    void on();
    void off();
}

// 具体设备
public class SmartLight implements SmartDevice {
    public void on() {
        System.out.println("智能灯开启");
    }
    
    public void off() {
        System.out.println("智能灯关闭");
    }
}

// 场景命令
public class SceneCommand implements Command {
    private List<Command> commands = new ArrayList<>();
    
    public void addCommand(Command command) {
        commands.add(command);
    }
    
    public void execute() {
        for (Command command : commands) {
            command.execute();
        }
    }
    
    public void undo() {
        for (int i = commands.size() - 1; i >= 0; i--) {
            commands.get(i).undo();
        }
    }
}

// 使用场景命令
SceneCommand goodNightScene = new SceneCommand();
goodNightScene.addCommand(new LightOffCommand(livingRoomLight));
goodNightScene.addCommand(new ThermostatSetCommand(thermostat, 20));

remote.setCommand(goodNightScene);
remote.pressButton();  // 执行晚安场景

五、命令模式的变体

1. 宏命令(组合命令)

public class MacroCommand implements Command {
    private Command[] commands;
    
    public MacroCommand(Command[] commands) {
        this.commands = commands;
    }
    
    public void execute() {
        for (Command command : commands) {
            command.execute();
        }
    }
    
    public void undo() {
        for (int i = commands.length - 1; i >= 0; i--) {
            commands[i].undo();
        }
    }
}

2. 延迟执行命令

public class DelayedCommand implements Command {
    private Command command;
    private long delayMillis;
    
    public DelayedCommand(Command command, long delayMillis) {
        this.command = command;
        this.delayMillis = delayMillis;
    }
    
    public void execute() {
        new Thread(() -> {
            try {
                Thread.sleep(delayMillis);
                command.execute();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}

六、命令模式的优缺点

优点

  1. 解耦调用者与执行者:降低系统耦合度
  2. 易于扩展:新增命令不影响现有代码
  3. 支持撤销/重做:可维护命令历史
  4. 支持事务:可实现命令的原子执行
  5. 灵活组合:可组合多个命令形成宏命令

缺点

  1. 类数量增加:每个命令都需要一个具体类
  2. 复杂度增加:对简单操作可能过度设计
  3. 性能开销:命令对象创建和管理需要额外资源

七、最佳实践

  1. 合理设计命令粒度:避免命令过于简单或复杂
  2. 考虑线程安全:多线程环境下的命令执行
  3. 限制命令历史:避免撤销历史占用过多内存
  4. 使用对象池:对频繁创建的命令对象使用对象池
  5. 结合备忘录模式:增强撤销功能的灵活性

八、总结

命令模式是封装操作请求的强大工具,特别适用于:

  • 需要将请求调用者与执行者解耦的场景
  • 需要支持撤销/重做功能的系统
  • 需要实现事务或原子操作的场景
  • 需要排队或延迟执行请求的场景

在实际开发中,命令模式常见于:

  • GUI事件处理(如按钮点击)
  • 事务系统
  • 宏录制功能
  • 任务调度系统
  • 智能家居控制

正确使用命令模式可以提高系统的灵活性和可扩展性,但需要注意不要过度使用,对于简单操作直接调用可能更合适。

http://www.dtcms.com/a/118130.html

相关文章:

  • Java面试39-Zookeeper中的Watch机制的原理
  • 前端服务配置详解:从入门到实战
  • 鸿蒙版小红书如何让图库访问完全由“你”掌控
  • 2025.04.07【数据科学新工具】| dynverse:数据标准化、排序、模拟与可视化的综合解决方案
  • MQTT-Dashboard-数据集成-WebHook、日志管理
  • 深入理解STAR法则
  • 如何开通google Free Tier长期免费云服务器(1C/1G)
  • Python----计算机视觉处理(Opencv:道路检测之车道线显示)
  • SpringWebFlux测试:WebTestClient与StepVerifier
  • 学透Spring Boot — 010. 单元测试和Spring Test
  • 青少年编程与数学 02-015 大学数学知识点 08课题、信息论
  • MySQL + ngram 最佳实践:轻量级中文 混合内容全文搜索方案
  • 秒杀系统设计方案
  • 一周学会Pandas2 Python数据处理与分析-NumPy数组的索引和切片
  • ResNet改进(21):基于ECA注意力机制的ResNet18网络实现
  • golang 内存逃逸 栈与堆区别
  • 如何解决:http2: Transport received Server‘s graceful shutdown GOAWAY
  • qemu仿真调试esp32,以及安装版和vscode版配置区别
  • 字符串操作栈和队列
  • MES生产工单管理系统,Java+Vue,含源码与文档,实现生产工单全流程管理,提升制造执行效率与精准度
  • C++使用Qt Charts可视化大规模点集
  • matlab中排序函数sortrows的用法
  • 快速入手-前后端分离Python权限系统 基于Django5+DRF+Vue3.2+Element Plus+Jwt
  • SQL注入流量分析
  • 【算法】二分查找
  • 单片机实现触摸按钮执行自定义任务组件
  • IntelliJ IDEA下开发FPGA——FPGA开发体验提升__下
  • 量子计算模拟中的GPU加速:从量子门操作到Shor算法实现
  • 嵌入式硬件实战基础篇(三)-四层板PCB设计-步进电机驱动(TMC2208/TMC2209)
  • 双周报Vol.69: C FFI 支持 borrow、新增.mbt.md测试与调试、WASM 后端支持extern type..