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

打印结果:

相关推荐
码匠许师傅9 分钟前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
geovindu3 小时前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
czhc114007566310 小时前
2026-09-10 综合博客:异步异常 + 排查核实思维
命令模式
YHHLAI17 小时前
NestJS 后端开发实战:从设计模式到 CRUD 全栈
设计模式
2401_868534781 天前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析
吃饱了得干活1 天前
Java设计模式实战:一个支付模块的重构之旅,层层递进理解设计模式精髓
后端·设计模式·架构
vivo互联网技术2 天前
软件不是从数据开始,而是从现实开始 | KDC 系列 01
设计模式·架构·领域驱动设计
码匠许师傅2 天前
【设计模式精讲】27.模板方法模式(Template Method)
c++·设计模式·uml·模板方法模式
码匠许师傅2 天前
【设计模式精讲】28.访问者模式(Visitor)
java·设计模式·访问者模式
码匠许师傅2 天前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml