Python设计模式详解之14 —— 命令模式

命令模式 (Command Pattern) 是一种行为型设计模式,它将请求封装为对象,从而使您可以用不同的请求、队列或日志来参数化其他对象。命令模式还支持撤销操作。

在 Python 中,命令模式通常用来解耦命令的发送者(调用者)和接收者(执行者),使得命令的调用者不需要知道命令是如何执行的。


结构

  1. 命令接口 (Command): 定义执行操作的接口。
  2. 具体命令 (ConcreteCommand): 实现命令接口,定义执行者的操作。
  3. 接收者 (Receiver): 执行具体命令逻辑的对象。
  4. 调用者 (Invoker): 请求命令执行的对象。
  5. 客户端 (Client): 创建具体命令对象并配置调用者。

Python 实现

python 复制代码
from abc import ABC, abstractmethod

# Command 接口
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def undo(self):
        pass

# Receiver
class Light:
    def turn_on(self):
        print("The light is ON")

    def turn_off(self):
        print("The light is OFF")

# ConcreteCommand
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()

# Invoker
class RemoteControl:
    def __init__(self):
        self.command = None

    def set_command(self, command: Command):
        self.command = command

    def press_button(self):
        if self.command:
            self.command.execute()

    def press_undo(self):
        if self.command:
            self.command.undo()

# Client
if __name__ == "__main__":
    # 创建接收者
    light = Light()

    # 创建具体命令
    light_on = LightOnCommand(light)
    light_off = LightOffCommand(light)

    # 创建调用者
    remote = RemoteControl()

    # 打开灯
    remote.set_command(light_on)
    remote.press_button()
    remote.press_undo()

    print()

    # 关闭灯
    remote.set_command(light_off)
    remote.press_button()
    remote.press_undo()

输出结果

plaintext 复制代码
The light is ON
The light is OFF

The light is OFF
The light is ON

模式要点

  1. 解耦: 调用者和接收者被解耦,调用者不需要知道具体的接收者和执行逻辑。
  2. 扩展性: 可以轻松添加新命令,而不修改调用者或接收者的代码。
  3. 历史记录: 可以将命令存储起来用于日志记录或撤销功能。

优点

  • 更好地支持开闭原则(OCP)。
  • 提供了对命令的撤销和重做功能的支持。
  • 命令可以被记录、序列化,支持延迟执行。

缺点

  • 增加了类的数量(每个命令对应一个类)。
  • 对于简单的操作,可能显得过于复杂。

适用场景

  1. 需要将一组操作封装成对象。
  2. 希望记录操作历史、支持撤销和重做功能。
  3. 需要参数化某些行为或操作。

通过命令模式,可以更灵活地管理行为的调用和执行!

相关推荐
Damon小智3 分钟前
鸿蒙元服务深度实践:跨端唤醒与状态共享的设计模式
华为·设计模式·harmonyos
shaominjin1233 分钟前
单例模式:设计模式中的“独一无二“之道
android·单例模式·设计模式
胖哥真不错31 分钟前
Python基于PyTorch实现多输入多输出进行BP神经网络回归预测项目实战
pytorch·python·毕业设计·论文·毕设·多输入多输出·bp神经网络回归预测
合作小小程序员小小店1 小时前
web网页开发,旧版在线%考试,判题%系统demo,基于python+flask+随机分配考试题目,基于开发语言python,数据库mysql
开发语言·后端·python·mysql·flask·html5
dalalajjl2 小时前
爱派(AiPy):一个让大语言模型直接操作Python完成任务
python
景彡先生2 小时前
Python matplotlib详解:从入门到精通,数据可视化利器
python·信息可视化·matplotlib
程序员大雄学编程2 小时前
用Python来学微积分22-费马定理
人工智能·python·数学·微积分
deephub2 小时前
sklearn 特征选择实战:用 RFE 找到最优特征组合
人工智能·python·机器学习·sklearn·特征选择
程序员杰哥2 小时前
外包干了三年,快要废了。。。
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
咩?2 小时前
10.27-yolov5代码
人工智能·python·深度学习