非常好!现在我们来深入讲解行为型设计模式之一 ------ 命令模式(Command Pattern)。
我将通过:
✅ 定义解释 + 🎯 使用动机 + 🐍 Python 完整调用代码(含注释)
🧭 清晰类图 + 流程图 + 应用场景
来帮助你彻底理解命令模式的结构和用途。
🧠 一句话定义
命令模式将"请求的发出者"与"执行者"解耦,把请求封装成一个命令对象,实现"命令的记录、撤销、队列化"。
🎯 为什么需要命令模式?
问题 | 命令模式的解决方式 |
---|---|
客户端调用逻辑与功能耦合 | 通过封装命令解耦 |
请求历史无法回退/重做 | 命令可以记录、撤销、重做 |
调用命令前后逻辑复杂 | 命令对象可组合链式调用 |
多种请求要统一调度 | 命令队列统一处理 |
✅ 优点 vs ❌ 缺点
✅ 优点 | ❌ 缺点 |
---|---|
解耦调用者和执行者 | 类增多 |
支持撤销、重做 | 初学者易混淆结构 |
支持日志记录 | - |
命令灵活组合 | - |
🕹 示例场景:遥控器控制家电
遥控器(调用者)发出命令,但不关心命令如何执行。
🐍 Python 实现(含注释)
🎯 1️⃣ 命令接口(Command)
python
from abc import ABC, abstractmethod
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
💡 2️⃣ 接收者类(Receiver)
python
class Light:
def turn_on(self):
print("💡 灯已打开")
def turn_off(self):
print("🌑 灯已关闭")
🛠 3️⃣ 具体命令类(ConcreteCommand)
python
class LightOnCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.turn_on()
def undo(self):
self.light.turn_off()
class LightOffCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.turn_off()
def undo(self):
self.light.turn_on()
🎛️ 4️⃣ 调用者类(Invoker)
python
class RemoteControl:
def __init__(self):
self.history = []
def set_command(self, command: Command):
command.execute()
self.history.append(command) # 保存记录以便 undo
def undo_last(self): #队列处理逻辑
if self.history:
command = self.history.pop()
command.undo()
else:
print("❗ 无命令可撤销")
🧪 5️⃣ 客户端调用
python
light = Light()
on_cmd = LightOnCommand(light)
off_cmd = LightOffCommand(light)
remote = RemoteControl()
remote.set_command(on_cmd) # 💡 开灯
remote.set_command(off_cmd) # 🌑 关灯
remote.undo_last() # 🔁 撤销关灯 → 再次开灯
remote.undo_last() # 🔁 撤销开灯 → 关闭灯
✅ 输出结果
💡 灯已打开
🌑 灯已关闭
💡 灯已打开
🌑 灯已关闭
🧭 类图(Mermaid)
<<interface>> Command +execute() +undo() Light +turn_on() +turn_off() LightOnCommand LightOffCommand RemoteControl
🧭 流程图(Mermaid)
Client RemoteControl LightOnCommand Light set_command(Cmd) execute() turn_on() undo_last() undo() turn_off() Client RemoteControl LightOnCommand Light
🧠 应用场景总结
应用场景 | 示例 |
---|---|
图形软件操作 | 画图、撤销、重做 |
宏命令执行 | Photoshop 动作、键盘宏 |
事务/批量处理 | 数据库操作、文件系统命令队列 |
命令排队或延时执行 | 网络请求、打印任务队列 |
✅ 总结口诀
✅ 命令是"请求的对象化" :
让你像操作对象一样存储、传递、组合、撤销操作。
🔄 VS 其他模式
模式 | 区别 |
---|---|
命令模式 | 把行为封装成对象,可组合、记录、撤销 |
策略模式 | 封装算法,可以互换 |
状态模式 | 封装状态行为,改变行为逻辑 |
职责链模式 | 多个处理器传递请求 |
是否希望我把命令换成你自己的项目场景?比如控制模型加载、文本处理步骤、接口操作等,我可以帮你自定义实现 🧩