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

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

相关推荐
nwsuaf_huasir10 分钟前
深度学习1.3-软件篇-2025Pycharm添加导入anaconda中虚拟环境的python解释器以及相关Error解决方案
人工智能·python·深度学习
eybk26 分钟前
局域网文件传输器安卓版本+win版本
android·python
旦莫35 分钟前
Pytest教程: Pytest ini配置文件深度剖析
python·单元测试·自动化·pytest
天才测试猿37 分钟前
Jmeter压测实战:Jmeter二次开发之自定义函数
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·压力测试
haiyu_y1 小时前
Day 30 函数专题 1
python
培根芝士1 小时前
使用Scripting API获取CS2游戏数据
python·游戏
阿杰同学1 小时前
Java 设计模式 面试题及答案整理,最新面试题
java·开发语言·设计模式
CesareCheung1 小时前
用python写一个websocket接口,并用jmeter压测websocket接口
python·websocket·jmeter
喜乐boy2 小时前
CV系列——Conda + PyTorch + CUDA + cuDNN + Python 环境无脑安装速查笔记[2025.12]
pytorch·python·conda·cuda·cv
@游子2 小时前
Python学习笔记-Day6
笔记·python·学习