命令模式(Command Pattern)

非常好!现在我们来深入讲解行为型设计模式之一 ------ 命令模式(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 其他模式

模式 区别
命令模式 把行为封装成对象,可组合、记录、撤销
策略模式 封装算法,可以互换
状态模式 封装状态行为,改变行为逻辑
职责链模式 多个处理器传递请求

是否希望我把命令换成你自己的项目场景?比如控制模型加载、文本处理步骤、接口操作等,我可以帮你自定义实现 🧩

相关推荐
Cuit小唐4 天前
Qt二维码demo
开发语言·qt·命令模式
碎梦归途7 天前
23种设计模式-行为型模式之命令模式(Java版本)
java·开发语言·jvm·设计模式·命令模式·行为型模式
冰茶_9 天前
C#中常见的设计模式
java·开发语言·microsoft·设计模式·微软·c#·命令模式
Sunlight_7779 天前
第六章 QT基础:6、QT的Qt 时钟编程
开发语言·qt·命令模式
ChoSeitaku10 天前
17.QT-Qt窗口-工具栏|状态栏|浮动窗口|设置停靠位置|设置浮动属性|设置移动属性|拉伸系数|添加控件(C++)
c++·qt·命令模式
kfepiza16 天前
用sed替换文本 笔记250419
linux·笔记·bash·命令模式
小马爱打代码20 天前
设计模式:命令模式-解耦请求与执行的完美方案
设计模式·命令模式
g20040733121 天前
excel 操作
命令模式
Cuit小唐21 天前
多线性读取数据实现QCustomPlot瀑布图
命令模式