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. 需要参数化某些行为或操作。

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

相关推荐
农夫山泉2号1 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI2 小时前
Flask Docker Demo 项目指南
python·docker·flask
码上淘金6 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo6 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552877 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子7 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174297 小时前
Python Day23 学习
python·学习
Ai尚研修-贾莲8 小时前
Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
python·信息可视化·数据分析·地球科学
qq_508576099 小时前
if __name__ == ‘__main__‘
python
学地理的小胖砸9 小时前
【Python 基础语法】
开发语言·python