命令模式
字数: 0

基本概念

Command Pattern: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queues, or log requests, and supports undoable operations.
notion image
封装的不是一个实例,而是一个动作(类似 Controller、Mapper 层?)

实现代码

命令

接收者

Receiver

触发者

Invoker

测试类

Q & A

What are the key advantages associated with command patterns?
  • Requests for creation and the ultimate execution are decoupled. Clients may not know how an invoker is performing the operations.
  • You can create macros (sequence of commands).
  • New commands can be added without affecting the existing system.
  • Most importantly, you can support the undo/redo operations.

具体应用

java.lang.Runnable

该接口的所有实现(作为接受者)都是命令者模式的例子
notion image
Runnable 接口通常用于定义线程执行的任务。当创建一个 Runnable 实现并将其提交给一个线程,实际上是在定义一个要执行的命令,将其交给调用者(Thread)执行。
2023 - 2026