19、命令模式(Command Pattern,不常用)

命令模式,将一个请求封装为一个对象(命令),使发出请求的责任和执行请求的责任分割开,有效降低系统的耦合度。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。命令模式包含以下主要角色:

  • 抽象命令类(Command):执行命令的接口,定义执行命令的抽象方法execute()。
  • 具体命令类(Concrete Command):抽象命令类的实现类,持有接收者对象,并在接收到命令后调用命令执行者的方法action()实现命令的调用和执行。
  • 命令执行者(Receiver):命令的具体执行者,定义了命令执行的具体方法action()。
  • 命令调用者(Invoker):接收客户端的命令并异步执行。

UML设计图如下:

1)Command 接口:

java 复制代码
public interface Command {
    void exe(String command);
}

2)命令的接收和执行者类Receiver:

java 复制代码
@Slf4j
public class Receiver {
    public void action(String commandMsg) {
        log.info("received command and execute command ...");
    }
}

3)Command 接口的实现类 ConcreteCommand:

java 复制代码
public class ConcreteCommand implements Command {
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void exe(String command) {
        receiver.action(command);
    }
}

4)命令调用者类 Invoker:

java 复制代码
@Slf4j
public class Invoker {
    private Command command;

    public Invoker(Command command) {
        this.command = command;
    }

    public void action(String commandMsg) {
        log.info("command sending ...");
        command.exe(commandMsg);
    }
}

5)测试命令模式:

java 复制代码
public class CommandTest {

    public static void main(String[] args) {
        // 定义命令的接收者和执行者
        Receiver receiver = new Receiver();
        // 命令实现者
        ConcreteCommand command = new ConcreteCommand(receiver);
        // 定义命令调用者
        Invoker invoker = new Invoker(command);
        // 调用命令
        invoker.action("cmd");
    }
}

打印结果:

相关推荐
AI酒旅实战开发4 小时前
旅行 AI Agent 的 7 种设计模式:从工具调用到交易闭环
人工智能·设计模式
geovindu2 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu3 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh8 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊9 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3339 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx10 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥10 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户6242931966211 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊11 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式