命令模式(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 其他模式

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

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

相关推荐
阿波罗尼亚5 天前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
共享家95277 天前
QT-系统(文件)
开发语言·qt·命令模式
iFlow_AI9 天前
增强AI编程助手效能:使用开源Litho(deepwiki-rs)深度上下文赋能iFlow
人工智能·ai·ai编程·命令模式·iflow·iflow cli·心流ai助手
o0向阳而生0o12 天前
112、23种设计模式之命令模式(20/23)
设计模式·命令模式
郝学胜-神的一滴24 天前
深入解析C++命令模式:设计原理与实际应用
开发语言·c++·程序人生·软件工程·命令模式
紫荆鱼1 个月前
设计模式-命令模式(Command)
c++·后端·设计模式·命令模式
杯莫停丶1 个月前
设计模式之:命令模式
设计模式·命令模式·1024程序员节·活动勋章
1379号监听员_1 个月前
嵌入式软件架构--显示界面架构(工厂流水线模型,HOME界面,命令界面)
stm32·单片机·架构·命令模式
太过平凡的小蚂蚁1 个月前
解耦的艺术:深入理解设计模式之命令模式
设计模式·命令模式
序属秋秋秋1 个月前
《Linux系统编程之入门基础》【Linux基础 理论+命令】(上)
linux·运维·服务器·ubuntu·centos·命令模式