Python设计模式:命令模式

news2025/4/18 4:13:49

1. 什么是命令模式?

命令模式是一种行为设计模式,它将请求封装为一个对象,从而使您能够使用不同的请求、队列或日志请求,以及支持可撤销操作。
命令模式的核心思想是将请求的发送者与请求的接收者解耦,使得两者之间的交互更加灵活。

1.1 命令模式的组成部分

命令模式通常包含以下几个组成部分,每个部分都有其特定的角色和功能。下面将详细介绍每个组成部分,并提供相应的代码示例。

1.1.1 命令接口(Command Interface)

命令接口定义了一个执行操作的接口,通常包含一个 execute 方法。所有具体命令类都需要实现这个接口。

# 命令接口
class Command:
    def execute(self):
        pass

1.1.2 具体命令类(Concrete Command)

具体命令类实现命令接口,定义与接收者之间的绑定关系,并调用接收者的相应操作。每个具体命令类都对应一个特定的操作。

# 接收者
class Light:
    def turn_on(self):
        print("The light is ON")

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

# 具体命令类
class LightOnCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.turn_on()

class LightOffCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.turn_off()

1.1.3 接收者(Receiver)

接收者是具体的业务逻辑类,包含实际执行操作的方法。命令对象会调用接收者的方法来完成请求。

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

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

1.1.4 调用者(Invoker)

调用者持有命令对象并在适当的时候调用命令的 execute 方法。调用者不需要知道命令的具体实现,只需调用命令接口。

示例代码
class RemoteControl:
    def __init__(self):
        self.command = None

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

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

1.1.5 客户端(Client)

客户端负责创建具体命令对象并设置接收者。客户端代码通常会将命令对象传递给调用者。

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

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

    # 创建调用者
    remote = RemoteControl()

    # 开灯
    remote.set_command(light_on)
    remote.press_button()  # 输出: The light is ON

    # 关灯
    remote.set_command(light_off)
    remote.press_button()  # 输出: The light is OFF
  1. 命令接口:定义了一个命令接口 Command,包含一个 execute 方法,所有具体命令类都需要实现这个方法。

  2. 具体命令类LightOnCommandLightOffCommand 实现了命令接口,分别用于打开和关闭灯。它们持有一个 Light 对象的引用,并在 execute 方法中调用相应的接收者方法。

  3. 接收者Light 类是接收者,包含实际执行操作的方法 turn_onturn_off

  4. 调用者RemoteControl 类持有命令对象,并在适当的时候调用命令的 execute 方法。它提供了 set_command 方法来设置命令对象。

  5. 客户端代码:在客户端代码中,创建接收者、具体命令和调用者,并通过调用者执行命令。客户端代码不需要知道命令的具体实现,只需使用命令接口。

1.2 命令模式的优点

1.2.1 解耦

说明:命令模式通过将请求的发送者与接收者解耦,使得发送者不需要知道接收者的具体实现。这种解耦使得系统更加灵活,便于维护和扩展。

1. 灵活性:发送者可以在不修改代码的情况下替换接收者。
# 接收者
class Light:
    def turn_on(self):
        print("The light is ON")

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

# 具体命令类
class LightOnCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.turn_on()

# 新的接收者
class Fan:
    def turn_on(self):
        print("The fan is ON")

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

# 客户端代码
light = Light()
fan = Fan()

light_on_command = LightOnCommand(light)
light_on_command.execute()  # 输出: The light is ON

# 替换接收者
fan_on_command = LightOnCommand(fan)  # 这里可以直接替换为 Fan
fan_on_command.execute()  # 输出: The fan is ON
2. 可维护性:修改接收者的实现不会影响发送者。
# 修改接收者的实现
class Light:
    def turn_on(self):
        print("The light is now ON")

# 客户端代码
light = Light()
light_on_command = LightOnCommand(light)
light_on_command.execute()  # 输出: The light is now ON
3. 可扩展性:轻松添加新命令而不修改现有代码。
# 新的具体命令类
class LightOffCommand(Command):
    def __init__(self, light):
        self.light = light

    def execute(self):
        self.light.turn_off()

# 客户端代码
light_off_command = LightOffCommand(light)
light_off_command.execute()  # 输出: The light is OFF
4. 支持多种请求:可以处理不同类型的请求。
# 另一个具体命令类
class FanOnCommand(Command):
    def __init__(self, fan):
        self.fan = fan

    def execute(self):
        self.fan.turn_on()

# 客户端代码
fan_on_command = FanOnCommand(fan)
fan_on_command.execute()  # 输出: The fan is ON

如果不采用解耦的设计,可能会面临以下风险:

1. 紧耦合:请求的发送者和接收者之间的紧耦合关系。
# 紧耦合示例
class RemoteControl:
    def __init__(self):
        self.light = Light()  # 直接依赖于具体的接收者

    def turn_on_light(self):
        self.light.turn_on()

# 客户端代码
remote = RemoteControl()
remote.turn_on_light()  # 输出: The light is ON
2. 难以扩展:添加新功能需要修改现有代码。
# 添加新功能需要修改现有代码
class RemoteControl:
    def __init__(self):
        self.light = Light()
        self.fan = Fan()  # 需要修改代码以添加新功能

    def turn_on_light(self):
        self.light.turn_on()

    def turn_on_fan(self):
        self.fan.turn_on()

# 客户端代码
remote = RemoteControl()
remote.turn_on_fan()  # 输出: The fan is ON

1.2.2 可扩展性

说明:可以轻松添加新的命令,而不需要修改现有代码。只需创建新的命令类并实现命令接口即可。

示例代码
# 新的具体命令类
class FanOffCommand(Command):
    def __init__(self, fan):
        self.fan = fan

    def execute(self):
        self.fan.turn_off()

# 客户端代码
fan_off_command = FanOffCommand(fan)
fan_off_command.execute()  # 输出: The fan is OFF

1.2.3 支持撤销操作

说明:可以通过维护命令的历史记录来实现撤销操作。每个命令对象可以记录其执行的状态,以便在需要时进行撤销。

示例代码
class CommandHistory:
    def __init__(self):
        self.history = []

    def push(self, command):
        self.history.append(command)

    def pop(self):
        if self.history:
            return self.history.pop()
        return None

# 客户端代码
history = CommandHistory()

# 执行命令
history.push(light_on_command)
light_on_command.execute()  # 输出: The light is ON

# 撤销命令
last_command = history.pop()
if last_command:
    print("Undoing last command...")
    # 这里可以实现撤销逻辑,例如不绘制图形

1.2.4 支持队列请求

说明:可以将请求放入队列中,按顺序执行。这使得命令模式非常适合处理异步请求或批量操作。

示例代码
from collections import deque

class CommandQueue:
    def __init__(self):
        self.queue = deque()

    def add_command(self, command):
        self.queue.append(command)

    def execute_commands(self):
        while self.queue:
            command = self.queue.popleft()
            command.execute()

# 客户端代码
command_queue = CommandQueue()
command_queue.add_command(light_on_command)
command_queue.add_command(fan_on_command)

# 执行所有命令
command_queue.execute_commands()
# 输出:
# The light is ON
# The fan is ON

2. 示例 1:命令模式在文本编辑器中的应用

命令模式是一种强大的设计模式,能够有效地解耦请求的发送者与接收者,提高代码的灵活性和可维护性。在本文中,我们将通过一个文本编辑器的示例,展示如何使用命令模式来实现文本操作(如插入、删除和撤销)。

# 命令接口
class Command:
    def execute(self):
        pass

    def undo(self):
        pass


# 接收者
class TextEditor:
    def __init__(self):
        self.text = ""

    def insert(self, text):
        self.text += text
        print(f"Inserted: '{text}' | Current text: '{self.text}'")

    def delete(self, length):
        deleted_text = self.text[-length:] if length <= len(self.text) else self.text
        self.text = self.text[:-length]
        print(f"Deleted: '{deleted_text}' | Current text: '{self.text}'")


# 具体命令类
class InsertCommand(Command):
    def __init__(self, editor, text):
        self.editor = editor
        self.text = text

    def execute(self):
        self.editor.insert(self.text)

    def undo(self):
        self.editor.delete(len(self.text))


class DeleteCommand(Command):
    def __init__(self, editor, length):
        self.editor = editor
        self.length = length
        self.deleted_text = ""

    def execute(self):
        self.deleted_text = self.editor.text[-self.length:] if self.length <= len(
            self.editor.text) else self.editor.text
        self.editor.delete(self.length)

    def undo(self):
        self.editor.insert(self.deleted_text)


# 调用者
class CommandHistory:
    def __init__(self):
        self.history = []

    def push(self, command):
        self.history.append(command)

    def pop(self):
        if self.history:
            return self.history.pop()
        return None


class CommandQueue:
    def __init__(self):
        self.queue = []

    def add_command(self, command):
        self.queue.append(command)

    def execute_commands(self, history):
        while self.queue:
            command = self.queue.pop(0)
            command.execute()
            history.push(command)  # 将执行的命令添加到历史记录中


# 客户端代码
if __name__ == "__main__":
    # 创建接收者
    editor = TextEditor()
    history = CommandHistory()
    command_queue = CommandQueue()

    # 创建并执行插入命令
    print("Executing insert commands:")
    insert_command1 = InsertCommand(editor, "Hello, ")
    command_queue.add_command(insert_command1)

    insert_command2 = InsertCommand(editor, "World!")
    command_queue.add_command(insert_command2)

    # 执行所有命令并记录到历史
    command_queue.execute_commands(history)

    # 预期输出: "Inserted: 'Hello, ' | Current text: 'Hello, '"
    # 预期输出: "Inserted: 'World!' | Current text: 'Hello, World!'"
    print(f"Current text after insertions: '{editor.text}'")  # 输出: Hello, World!

    # 撤销最后一个命令(插入)
    print("\nUndoing last insert command:")
    last_command = history.pop()
    if last_command:
        last_command.undo()  # 撤销插入操作

    # 预期输出: "Deleted: 'World!' | Current text: 'Hello, '"
    print(f"Current text after undo: '{editor.text}'")  # 输出: Hello,

    # 创建并执行删除命令
    print("\nExecuting delete command:")
    delete_command = DeleteCommand(editor, 6)
    command_queue.add_command(delete_command)
    command_queue.execute_commands(history)

    # 预期输出: "Deleted: 'Hello, ' | Current text: ''"
    print(f"Current text after deletion: '{editor.text}'")  # 输出: (空字符串)

    # 撤销删除命令
    print("\nUndoing delete command:")
    last_command = history.pop()
    if last_command:
        last_command.undo()  # 撤销删除操作

    # 预期输出: "Inserted: 'Hello, ' | Current text: 'Hello, '"
    print(f"Current text after undo delete: '{editor.text}'")  # 输出: Hello,

    # 最终状态
    print(f"\nFinal text: '{editor.text}'")  # 输出最终文本状态

Executing insert commands:
Inserted: 'Hello, ' | Current text: 'Hello, '
Inserted: 'World!' | Current text: 'Hello, World!'
Current text after insertions: 'Hello, World!'

Undoing last insert command:
Deleted: 'World!' | Current text: 'Hello, '
Current text after undo: 'Hello, '

Executing delete command:
Deleted: 'ello, ' | Current text: 'H'
Current text after deletion: 'H'

Undoing delete command:
Inserted: 'ello, ' | Current text: 'Hello, '
Current text after undo delete: 'Hello, '

Final text: 'Hello, '
  1. 命令接口:定义了一个命令接口 Command,包含 executeundo 方法。所有具体命令类都需要实现这两个方法。

  2. 接收者TextEditor 类是接收者,包含实际执行操作的方法 insertdelete。这些方法负责修改文本状态并输出当前文本。

  3. 具体命令类

    • InsertCommand 用于插入文本。它持有一个 TextEditor 对象的引用,并在 execute 方法中调用 insert 方法。在 undo 方法中调用 delete 方法以撤销插入操作。
    • DeleteCommand 用于删除文本。它同样持有一个 TextEditor 对象的引用,并在 execute 方法中调用 delete 方法。在 undo 方法中调用 insert 方法以撤销删除操作。
  4. 调用者

    • CommandHistory 类用于维护命令的历史记录,以支持撤销操作。它提供 pushpop 方法来管理命令历史。
    • CommandQueue 类用于将命令放入队列中,按顺序执行,并在执行时将命令添加到历史记录中。
  5. 客户端代码:在客户端代码中,创建接收者、具体命令和调用者,并通过调用者执行命令。每个执行的命令都会被记录到 CommandHistory 中,以便后续撤销。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2332640.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

华为手机或平板与电脑实现文件共享

1.手机或平板与电脑在同一个网络 2.打开手机或平板端&#xff0c;设置---更多连接----快分享或华为分享打开此功能-----开启共享至电脑 3.打开电脑&#xff0c;网络中就可看到手机端分享的用户名称 4. 登陆就可访问手机 5.常见问题 5.1 电脑未发现本机 5.2 修改了访问密码后再…

幻兽帕鲁(Palworld)在线工具集:让游戏体验更轻松!

幻兽帕鲁(Palworld)在线工具集&#xff1a;让游戏体验更轻松&#xff01; &#x1f3ae; 工具介绍 为了帮助广大幻兽帕鲁玩家更好地享受游戏&#xff0c;我开发了这个全面的在线工具集。无需下载安装&#xff0c;打开网页即可使用&#xff0c;完全免费&#xff01; &#x1…

学习51单片机Day02---实验:点亮一个LED灯

目录 1.先看原理图 2.思考一下&#xff08;sbit的使用&#xff09;&#xff1a; 3.给0是要让这个LED亮&#xff08;LED端口设置为低电平&#xff09; 4.完成的代码 1.先看原理图 比如我们要让LED3亮起来&#xff0c;对应的是P2^2。 2.思考一下&#xff08;sbit的使用&…

如何使用通义灵码学习JavaScript和DOM

如果你看到了本手册的页面数量&#xff0c;你就会发现JavaScript的API真的非常丰富&#xff0c;在MDN上专门有一大分类用于介绍JavaScript的API&#xff0c;但软件工程行业有一个著名法则叫2-8法则&#xff0c;意思是只有20%的内容会经常使用到&#xff0c;而80%的内容只在一些…

基于labview的多功能数据采集系统

基于labview的多功能数据采集系统&#xff08;可定制功能&#xff09; 包含基于NI温度采集卡。电流采集卡。电压采集卡的数据采集功能 数据存储 报表存储 数据处理与分析 生产者消费者架构 有需要可联系

SpringMVC基础一(SpringMVC运行原理)

先了解MVC&#xff0c;在JavaWeb基础五中。 回忆servlet&#xff0c;在javaweb基础二中。 创建一个web项目&#xff1a; 1、新建maven项目&#xff0c;导入依赖。&#xff08;junit、springmvc、spring-webmvc、servlet-api、jsp-api、jstl&#xff09; <groupId>org…

蓝桥杯刷题--宝石组合

在一个神秘的森林里&#xff0c;住着一个小精灵名叫小蓝。有一天&#xff0c;他偶然发现了一个隐藏在树洞里的宝藏&#xff0c;里面装满了闪烁着美丽光芒的宝石。这些宝石都有着不同的颜色和形状&#xff0c;但最引人注目的是它们各自独特的 “闪亮度” 属性。每颗宝石都有一个…

红宝书第三十一讲:通俗易懂的包管理器指南:npm 与 Yarn

红宝书第三十一讲&#xff1a;通俗易懂的包管理器指南&#xff1a;npm 与 Yarn 资料取自《JavaScript高级程序设计&#xff08;第5版&#xff09;》。 查看总目录&#xff1a;红宝书学习大纲 一、基础概念 包管理器&#xff1a;帮你自动下载和管理第三方代码库&#xff08;如…

进程状态的转换

进程处于运行态时&#xff0c;它必须已获得所需的资源&#xff0c;在运行结束后就撤销。只有在时间片到或出现了比现在进程优先级更高的进程时才转变成就绪态。 就绪 → 运行​​ ​​触发条件​​&#xff1a;进程被​​调度器选中​​&#xff08;如时间片轮转或优先级调度&…

SpringAOP新链浅析

前言 在复现CCSSSC软件攻防赛的时候发现需要打SpringAOP链子&#xff0c;于是跟着前人的文章自己动手调试了一下 参考了大佬的文章 https://gsbp0.github.io/post/springaop/#%E6%B5%81%E7%A8%8B https://mp.weixin.qq.com/s/oQ1mFohc332v8U1yA7RaMQ 正文 依赖于Spring-AO…

【动手学深度学习】现代卷积神经网络:ALexNet

【动手学深度学习】现代卷积神经网络&#xff1a;ALexNet 1&#xff0c;ALexNet简介2&#xff0c;AlexNet和LeNet的对比3&#xff0c; AlexNet模型详细设计4&#xff0c;AlexNet采用ReLU激活函数4.1&#xff0c;ReLU激活函数4.2&#xff0c;sigmoid激活函数4.3&#xff0c;为什…

PyTorch深度学习框架60天进阶学习计划 - 第37天:元学习框架

PyTorch深度学习框架60天进阶学习计划 - 第37天&#xff1a;元学习框架 嘿&#xff0c;朋友们&#xff01;欢迎来到我们PyTorch进阶之旅的第37天。今天我们将深入探索一个非常有趣且强大的领域——元学习(Meta-Learning)&#xff0c;也被称为"学会学习"(Learning to…

【中检在线-注册安全分析报告】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 1. 暴力破解密码&#xff0c;造成用户信息泄露 2. 短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉 3. 带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造…

UE5 运行时动态将玩家手部模型设置为相机的子物体

在编辑器里&#xff0c;我们虽然可以手动添加相机&#xff0c;但是无法将网格体设置为相机的子物体&#xff0c;只能将相机设置为网格体的子物体 但是为了使用方便&#xff0c;我们希望将网格体设置为相机的子物体&#xff0c;这样我们直接旋转相机就可以旋转网格体&#xff0…

EasyExcel-一款好用的excel生成工具

EasyExcel是一款处理excel的工具类&#xff0c;主要特点如下&#xff08;官方&#xff09;&#xff1a; 特点 高性能读写&#xff1a;FastExcel 专注于性能优化&#xff0c;能够高效处理大规模的 Excel 数据。相比一些传统的 Excel 处理库&#xff0c;它能显著降低内存占用。…

WEB攻防-Java安全JNDIRMILDAP五大不安全组件RCE执行不出网不回显

目录 1. RCE执行-5大类函数调用 1.1 Runtime方式 1.2 Groovy执行命令 1.3 脚本引擎代码注入 1.4 ProcessImpl 1.5 ProcessBuilder 2. JNDI注入(RCE)-RMI&LDAP&高版本 2.1 RMI服务中的JNDI注入场景 2.2 LDAP服务中的JNDI注入场景 攻击路径示例&#…

DrissionPage移动端自动化:从H5到原生App的跨界测试

一、移动端自动化测试的挑战与机遇 移动端测试面临多维度挑战&#xff1a; 设备碎片化&#xff1a;Android/iOS版本、屏幕分辨率差异 混合应用架构&#xff1a;H5页面与原生组件的深度耦合 交互复杂性&#xff1a;多点触控、手势操作、传感器模拟 性能监控&#xff1a;内存…

从 Excel 到你的表格应用:条件格式功能的嵌入实践指南

一、引言 在日常工作中&#xff0c;面对海量数据时&#xff0c;如何快速识别关键信息、发现数据趋势或异常值&#xff0c;是每个数据分析师面临的挑战。Excel的条件格式功能通过自动化的视觉标记&#xff0c;帮助用户轻松应对这一难题。 本文将详细介绍条件格式的应用场景&am…

STM32单片机入门学习——第22节: [7-2] AD单通道AD多通道

写这个文章是用来学习的,记录一下我的学习过程。希望我能一直坚持下去,我只是一个小白,只是想好好学习,我知道这会很难&#xff0c;但我还是想去做&#xff01; 本文写于&#xff1a;2025.04.07 STM32开发板学习——第22节: [7-2] AD单通道&AD多通道 前言开发板说明引用解…

【Survival Analysis】【机器学习】【1】

前言&#xff1a; 今年在做的一个博士课题项目&#xff0c;主要是利用病人的数据&#xff0c;训练出一个AI模型&#xff0c;做因果分析&#xff0c; 以及个性化治疗。自己一直是做通讯AI方向的&#xff0c;这个系列主要参考卡梅隆大学的教程&#xff0c;以及临床医生的角度 了…