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");
    }
}

打印结果:

相关推荐
Pkmer4 小时前
古法编程: 适配器模式
java·设计模式
灰子学技术19 小时前
Envoy 使用的设计模式技术文档
设计模式
Carl_奕然1 天前
【智能体】Agent的四种设计模式之:ReAct
人工智能·设计模式·语言模型
二哈赛车手1 天前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
楼田莉子1 天前
仿Muduo的高并发服务器:Channel模块与Poller模块
linux·服务器·c++·学习·设计模式
geovindu2 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
嵌入式学习_force2 天前
02_state
设计模式·蓝牙
qcx232 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
Cosolar3 天前
提示词工程面试题系列 - Zero-Shot Prompting 和 Few-Shot Prompting 的核心区别是什么?
人工智能·设计模式·架构
geovindu3 天前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式