Python设计模式:命令模式

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 = lightdef execute(self):self.light.turn_on()class LightOffCommand(Command):def __init__(self, light):self.light = lightdef 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 = Nonedef set_command(self, command):self.command = commanddef 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 = lightdef 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 = lightdef 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 = fandef 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 = fandef 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 dequeclass 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):passdef undo(self):pass# 接收者
class TextEditor:def __init__(self):self.text = ""def insert(self, text):self.text += textprint(f"Inserted: '{text}' | Current text: '{self.text}'")def delete(self, length):deleted_text = self.text[-length:] if length <= len(self.text) else self.textself.text = self.text[:-length]print(f"Deleted: '{deleted_text}' | Current text: '{self.text}'")# 具体命令类
class InsertCommand(Command):def __init__(self, editor, text):self.editor = editorself.text = textdef 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 = editorself.length = lengthself.deleted_text = ""def execute(self):self.deleted_text = self.editor.text[-self.length:] if self.length <= len(self.editor.text) else self.editor.textself.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 Noneclass 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.mzph.cn/bicheng/76814.shtml

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

相关文章

nlp面试重点

深度学习基本原理&#xff1a;梯度下降公式&#xff0c;将损失函数越来越小&#xff0c;最终预测值和实际值误差比较小。 交叉熵&#xff1a;-p(x)logq(x)&#xff0c;p(x)是one-hot形式。如果不使用softmax计算交叉熵&#xff0c;是不行的。损失函数可能会非常大&#xff0c;…

Leetcode:二叉树

94. 二叉树的中序遍历 class Solution {public List<Integer> inorderTraversal(TreeNode root) {TreeNode cur root;Stack<TreeNode> stack new Stack<>();List<Integer> list new ArrayList<>();while (!stack.isEmpty() || cur ! null) {…

SQL:Constraint(约束)

目录 &#x1f3af; 什么是 Constraint&#xff1f; MySQL 中常见的约束类型&#xff1a; 1. PRIMARY KEY 2. FOREIGN KEY 3. UNIQUE 4. NOT NULL 5. DEFAULT 6. CHECK&#xff08;MySQL 8.0&#xff09; 7. AUTO_INCREMENT &#x1f3af; 什么是 Constraint&#xf…

数据库数据恢复——sql server数据库被加密怎么恢复数据?

SQL server数据库数据故障&#xff1a; SQL server数据库被加密&#xff0c;无法使用。 数据库MDF、LDF、log日志文件名字被篡改。 数据库备份被加密&#xff0c;文件名字被篡改。 SQL server数据库数据恢复过程&#xff1a; 1、将所有数据库做完整只读备份。后续所有数据恢…

MySQL 用 limit 影响性能的优化方案

一.使用索引覆盖扫描 如果我们只需要查询部分字段&#xff0c;而不是所有字段&#xff0c;我们可以尝试使用索引覆盖扫描&#xff0c;也就是让查询所需的所有字段都在索引中&#xff0c;这样就不需要再访问数据页&#xff0c;减少了随机 I/O 操作。 例如&#xff0c;如果我们…

【算法笔记】并查集详解

&#x1f680; 并查集&#xff08;Union-Find&#xff09;详解&#xff1a;原理、实现与优化 并查集&#xff08;Union-Find&#xff09;是一种非常高效的数据结构&#xff0c;用于处理动态连通性问题&#xff0c;即判断若干个元素是否属于同一个集合&#xff0c;并支持集合合…

鸿蒙HarmonyOS埋点SDK,ClkLog适配鸿蒙埋点分析

ClkLog埋点分析系统&#xff0c;是一种全新的、开源的洞察方案&#xff0c;它能够帮助您捕捉每一个关键数据点&#xff0c;确保您的决策基于最准确的用户行为分析。技术人员可快速搭建私有的分析系统。 ClkLog鸿蒙埋点SDK通过手动埋点的方式实现HarmonyOS 原生应用的前端数据采…

JMeter的关联

关联&#xff1a;上一个请求的响应结果和下一个请求的数据有关系 xpath提取器 适用场景 HTML/XML文档结构化数据&#xff1a; 适用于从HTML或XML文档中提取结构化数据。例如&#xff0c;提取表格中的数据、列表中的项目等。示例&#xff1a;从HTML表格中提取所有行数据。 …

Spring Security 权限配置详解

&#x1f31f;Spring Security 权限配置详解&#xff1a;从基础到进阶 Spring Security 是一个功能强大、可高度自定义的安全框架&#xff0c;主要用于为基于 Spring 的应用程序提供身份验证和授权功能。 本篇文章将带你深入理解 Spring Security 的权限配置机制&#xff0c;掌…

pycharm中安装Charm-Crypto

一、安装依赖 1、安装gcc、make、perl sudo apt-get install gcc sudo apt-get install make sudo apt-get install perl #检查版本 gcc -v make -v perl -v 2、安装依赖库m4、flex、bison(如果前面安装过pypbc的话,应该已经装过这些包了) sudo apt-get update sudo apt…

【MCAL】AUTOSAR架构下基于SPI通信的驱动模块详解-以TJA1145为例

目录 前言 正文 1.TJA1145驱动代码中的SPI协议设计 1.1 对SPI Driver的依赖 1.2 对SPI配置的依赖 1.2.1 SpiExternalDevice 1.2.2 Channel_x 1.2.3 Job_x 1.2.4 Sequence N 1.2.5 Sequence M 1.2.6 Sequence L 1.2.7 小结 2.基于Vector驱动代码的SPI配置 2.1 SPI引…

JavaScript:BOM编程

今天我要介绍的是JS中有关于BOM编程的知识点内容&#xff1a;BOM编程&#xff1b; 介绍&#xff1a;BOM全名&#xff08;Browser Object Model&#xff08;浏览器对象模型&#xff09;&#xff09;。 是浏览器提供的与浏览器窗口交互的接口&#xff0c;其核心对象是 window。与…

Memcached缓存系统:从部署到实战应用指南

#作者&#xff1a;猎人 文章目录 一、安装libevent二、安装配置memcached三、安装Memcache的PHP扩展四、使用libmemcached的客户端工具五、Nginx整合memcached:六、php将会话保存至memcached Memcached是一款开源、高性能、分布式内存对象缓存系统&#xff0c;可应用各种需要缓…

解决前后端时区不一致问题

前后端时区不一致导致&#xff1a; 》数据不显示在前端 》页面显示时间有误 》一些对时间有要求的方法&#xff0c;无法正确执行&#xff0c;出现null值&#xff0c;加上我们对null值有判断/注解&#xff0c;程序就会报错中断&#xff0c;以为是业务逻辑问题&#xff0c;其实…

35.Java线程池(线程池概述、线程池的架构、线程池的种类与创建、线程池的底层原理、线程池的工作流程、线程池的拒绝策略、自定义线程池)

一、线程池概述 1、线程池的优势 线程池是一种线程使用模式&#xff0c;线程过多会带来调度开销&#xff0c;进而影响缓存局部性和整体性能&#xff0c;而线程池维护着多个线程&#xff0c;等待着监督管理者分配可并发执行的任务&#xff0c;这避免了在处理短时间任务时创建与…

驱动开发硬核特训 · Day 6 : 深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比

&#x1f50d; B站相应的视屏教程&#xff1a; &#x1f4cc; 内核&#xff1a;博文视频 - 从静态绑定驱动模型到现代设备模型 主题&#xff1a;深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比 在上一节中&#xff0c;我们从驱动框架的历史演进出…

Blender安装基础使用教程

本博客记录安装Blender和基础使用&#xff0c;可以按如下操作来绘制标靶场景、道路标识牌等。 目录 1.安装Blender 2.创建面板资源 步骤 1: 设置 Blender 场景 步骤 2: 创建一个平面 步骤 3: 将 PDF 转换为图像 步骤 4-方法1: 添加材质并贴图 步骤4-方法2&#xff1a;创…

智能手机功耗测试

随着智能手机发展,用户体验对手机的续航功耗要求越来越高。需要对手机进行功耗测试及分解优化,将手机的性能与功耗平衡。低功耗技术推动了手机的用户体验。手机功耗测试可以采用powermonitor或者NI仪表在功耗版上进行测试与优化。作为一个多功能的智能终端,手机的功耗组成极…

从代码学习深度学习 - 多头注意力 PyTorch 版

文章目录 前言一、多头注意力机制介绍1.1 工作原理1.2 优势1.3 代码实现概述二、代码解析2.1 导入依赖序列掩码函数2.2 掩码 Softmax 函数2.3 缩放点积注意力2.4 张量转换函数2.5 多头注意力模块2.6 测试代码总结前言 在深度学习领域,注意力机制(Attention Mechanism)是自然…

学术版 GPT 网页

学术版 GPT 网页 1. 学术版 GPT 网页非盈利版References https://academic.chatwithpaper.org/ 1. 学术版 GPT 网页非盈利版 arXiv 全文翻译&#xff0c;免费且无需登录。 更换模型 System prompt: Serve me as a writing and programming assistant. 界面外观 References …