设计模式——命令模式

命令模式简单学习

命令模式是一种行为设计模式,它把请求封装成对象,从而能够参数化方法调用、延迟调用执行、以及支持可撤销的操作。这种模式在很多情况下都非常有用,尤其是在需要将请求发送者和请求接收者解耦的情况下。

命令模式的基本概念

  1. 命令接口 (Command): 定义了所有命令都需要实现的一个公共接口。
  2. 具体命令 (ConcreteCommand): 实现命令接口,通常包含对接受者的引用。
  3. 接受者 (Receiver): 实现了命令所要执行的操作。
  4. 调用者 (Invoker): 请求命令来执行一个特定操作。

命令模式的结构

  • Command (命令接口)
    • execute(): 执行命令的方法。
  • ConcreteCommand (具体命令)
    • 包含接收者对象,并实现execute()方法。
  • Receiver (接收者)
    • 包含实际业务逻辑的方法。
  • Invoker (调用者)
    • 持有一个命令对象,并通过setCommand(Command command)设置命令,通过action()调用命令的execute()方法。

示例代码

有一个简单的遥控器和一些电器设备作为例子。

接收者(Receiver)
java 复制代码
public class Light {
    public void on() {
        System.out.println("Light is on");
    }

    public void off() {
        System.out.println("Light is off");
    }
}
命令接口(Command)
java 复制代码
public interface Command {
    void execute();
}
具体命令(ConcreteCommand)
java 复制代码
public class LightOnCommand implements Command {
    private Light light;

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

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

public class LightOffCommand implements Command {
    private Light light;

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

    @Override
    public void execute() {
        light.off();
    }
}
调用者(Invoker)
java 复制代码
public class RemoteControl {
    private Command command;

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

    public void pressButton() {
        command.execute();
    }
}
客户端代码
java 复制代码
public class Main {
    public static void main(String[] args) {
        Light livingRoomLight = new Light();
        Command lightOn = new LightOnCommand(livingRoomLight);
        Command lightOff = new LightOffCommand(livingRoomLight);

        RemoteControl remoteControl = new RemoteControl();

        // Turn the light on
        remoteControl.setCommand(lightOn);
        remoteControl.pressButton();

        // Turn the light off
        remoteControl.setCommand(lightOff);
        remoteControl.pressButton();
    }
}

使用场景

  • 解耦:当需要将请求发送者和接收者解耦时。
  • 可撤销/重做:当需要支持请求的撤销和重做操作时。
  • 事务处理:当一组操作必须全部成功或者全部失败时。
  • 队列化:当需要将请求放入队列中,稍后处理时。
相关推荐
Yu_Lijing28 分钟前
基于C++的《Head First设计模式》笔记——命令模式
c++·笔记·设计模式
天“码”行空36 分钟前
java的设计模式-----------单例类
java·开发语言·设计模式
一条闲鱼_mytube1 小时前
智能体设计模式 - 核心精华
人工智能·设计模式
Engineer邓祥浩1 小时前
设计模式学习(11) 23-9 组合模式
学习·设计模式·组合模式
Engineer邓祥浩1 小时前
设计模式学习(13) 23-11 享元模式
学习·设计模式·享元模式
刀法如飞13 小时前
开箱即用的 DDD(领域驱动设计)工程脚手架,基于 Spring Boot 4.0.1 和 Java 21
java·spring boot·mysql·spring·设计模式·intellij-idea
GISer_Jing17 小时前
AI Agent 人类参与HITL与知识检索RAG
人工智能·设计模式·aigc
Tiny_React1 天前
Claude Code Skills 自优化架构设计
人工智能·设计模式
胖虎11 天前
iOS中的设计模式(十)- 中介者模式(从播放器场景理解中介者模式)
设计模式·中介者模式·解耦·ios中的设计模式
Geoking.1 天前
【设计模式】组合模式(Composite)详解
java·设计模式·组合模式