HoRain云--Python 命令模式

发布时间:2026/6/8 13:10:24

HoRain云--Python 命令模式 HoRain 云小助手个人主页⛺️生活的理想就是为了理想的生活!⛳️ 推荐前些天发现了一个超棒的服务器购买网站性价比超高大内存超划算忍不住分享一下给大家。点击跳转到网站。目录⛳️ 推荐生活中的类比为什么需要命令模式传统方式的局限性实例命令模式的优势命令模式的核心组件基本结构完整代码示例基础实现实例高级应用示例支持多设备的万能遥控器实例命令模式的参数和选项命令接口的扩展实例命令队列和延迟执行实例实践练习练习 1实现空调控制系统实例练习 2实现文本编辑器的撤销功能实例常见问题解答Q: 命令模式适用于什么场景Q: 命令模式的缺点是什么Q: 如何选择是否使用命令模式总结命令模式是一种行为设计模式它将一个请求封装成一个对象从而使你可以用不同的请求对客户进行参数化。简单来说命令模式把操作比如打开文件、保存数据包装成独立的对象让你能够像处理数据一样处理操作。生活中的类比想象一下餐厅的点餐流程顾客客户端不需要知道厨师如何做菜服务员调用者接收订单但不亲自烹饪订单命令对象包含了具体的菜品信息厨师接收者根据订单执行具体的烹饪操作这种分工明确的模式就是命令模式在现实生活中的体现。为什么需要命令模式传统方式的局限性在传统编程中我们通常直接调用对象的方法实例class Light:def turn_on(self):print(灯亮了)def turn_off(self):print(灯灭了)# 直接调用light Light()light.turn_on()light.turn_off()这种方式存在几个问题紧耦合调用者需要知道接收者的具体接口难以扩展添加新功能需要修改现有代码不支持撤销/重做操作执行后无法回退命令模式的优势命令模式通过引入中间层命令对象解决了上述问题提供了解耦调用者与接收者之间没有直接依赖可扩展性容易添加新的命令支持撤销/重做可以记录操作历史队列支持可以将命令放入队列延迟执行命令模式的核心组件基本结构命令模式包含四个核心角色角色职责示例Command命令接口声明执行操作的接口execute(),undo()ConcreteCommand具体命令实现命令接口绑定接收者LightOnCommand,LightOffCommandReceiver接收者知道如何执行操作Light,TVInvoker调用者存储并执行命令RemoteControl完整代码示例基础实现让我们通过一个智能家居的灯光控制例子来理解命令模式实例from abc import ABC, abstractmethodfrom typing import List# 1. 命令接口class Command(ABC):abstractmethoddef execute(self):passabstractmethoddef undo(self):pass# 2. 接收者 - 灯光设备class Light:def turn_on(self):print(#x1f4a1; 灯光已打开)def turn_off(self):print(#x1f4a1; 灯光已关闭)# 3. 具体命令 - 开灯命令class LightOnCommand(Command):def __init__(self, light: Light):self.light lightdef execute(self):self.light.turn_on()def undo(self):self.light.turn_off()# 4. 具体命令 - 关灯命令class LightOffCommand(Command):def __init__(self, light: Light):self.light lightdef execute(self):self.light.turn_off()def undo(self):self.light.turn_on()# 5. 调用者 - 遥控器class RemoteControl:def __init__(self):self.command Noneself.history: List[Command] []def set_command(self, command: Command):self.command commanddef press_button(self):if self.command:self.command.execute()self.history.append(self.command)def press_undo(self):if self.history:last_command self.history.pop()last_command.undo()# 客户端代码if __name__ __main__:# 创建设备living_room_light Light()# 创建命令light_on LightOnCommand(living_room_light)light_off LightOffCommand(living_room_light)# 创建遥控器remote RemoteControl()# 测试开灯print( 测试开灯 )remote.set_command(light_on)remote.press_button()# 测试关灯print(\n 测试关灯 )remote.set_command(light_off)remote.press_button()# 测试撤销print(\n 测试撤销操作 )remote.press_undo() # 撤销关灯应该开灯remote.press_undo() # 撤销开灯应该关灯运行结果高级应用示例支持多设备的万能遥控器让我们扩展之前的例子创建一个支持多种设备的万能遥控器实例# 新增设备 - 电视class TV:def __init__(self, location: str):self.location locationself.is_on Falseself.volume 50def turn_on(self):self.is_on Trueprint(f#x1f4fa; {self.location}电视已打开)def turn_off(self):self.is_on Falseprint(f#x1f4fa; {self.location}电视已关闭)def set_volume(self, volume: int):self.volume volumeprint(f#x1f4fa; {self.location}电视音量设置为 {volume})# 电视相关命令class TVOnCommand(Command):def __init__(self, tv: TV):self.tv tvself.previous_volume 50def execute(self):self.previous_volume self.tv.volumeself.tv.turn_on()def undo(self):self.tv.turn_off()self.tv.volume self.previous_volumeclass TVVolumeUpCommand(Command):def __init__(self, tv: TV):self.tv tvself.previous_volume 50def execute(self):self.previous_volume self.tv.volumeself.tv.set_volume(min(100, self.tv.volume 10))def undo(self):self.tv.set_volume(self.previous_volume)# 宏命令 - 一键执行多个命令class MacroCommand(Command):def __init__(self, commands: List[Command]):self.commands commandsdef execute(self):for command in self.commands:command.execute()def undo(self):# 按相反顺序撤销for command in reversed(self.commands):command.undo()# 改进的遥控器class AdvancedRemoteControl:def __init__(self, slot_count: int 4):self.on_commands: List[Command] [None] * slot_countself.off_commands: List[Command] [None] * slot_countself.history: List[Command] []def set_command(self, slot: int, on_command: Command, off_command: Command):self.on_commands[slot] on_commandself.off_commands[slot] off_commanddef press_on_button(self, slot: int):if self.on_commands[slot]:self.on_commands[slot].execute()self.history.append(self.on_commands[slot])def press_off_button(self, slot: int):if self.off_commands[slot]:self.off_commands[slot].execute()self.history.append(self.off_commands[slot])def press_undo(self):if self.history:last_command self.history.pop()last_command.undo()# 测试高级遥控器def test_advanced_remote():print( 测试万能遥控器 )# 创建设备living_room_light Light()bedroom_tv TV(卧室)# 创建命令light_on LightOnCommand(living_room_light)light_off LightOffCommand(living_room_light)tv_on TVOnCommand(bedroom_tv)tv_volume_up TVVolumeUpCommand(bedroom_tv)# 创建宏命令 - 影院模式cinema_mode MacroCommand([light_off, tv_on, tv_volume_up])# 设置遥控器remote AdvancedRemoteControl()remote.set_command(0, light_on, light_off) # 槽位0灯光控制remote.set_command(1, tv_on, TVOnCommand(bedroom_tv)) # 槽位1电视控制remote.set_command(2, cinema_mode, light_on) # 槽位2影院模式# 测试各种功能print(\n1. 打开灯光:)remote.press_on_button(0)print(\n2. 开启影院模式:)remote.press_on_button(2)print(\n3. 撤销操作:)remote.press_undo()if __name__ __main__:test_advanced_remote()命令模式的参数和选项命令接口的扩展在实际应用中命令接口可以根据需要扩展更多功能实例class AdvancedCommand(ABC):abstractmethoddef execute(self):执行命令passabstractmethoddef undo(self):撤销命令passabstractmethoddef redo(self):重做命令passabstractmethoddef can_execute(self) - bool:检查命令是否可以执行passabstractmethoddef get_description(self) - str:获取命令描述pass命令队列和延迟执行命令模式天然支持命令队列这在很多场景下非常有用实例class CommandQueue:def __init__(self):self.queue: List[Command] []def add_command(self, command: Command):self.queue.append(command)def process_commands(self):while self.queue:command self.queue.pop(0)if command.can_execute():command.execute()def clear(self):self.queue.clear()实践练习练习 1实现空调控制系统尝试实现一个空调控制系统的命令模式实例# 你的代码在这里class AirConditioner:def __init__(self):self.temperature 26self.is_on Falsedef turn_on(self):# 实现打开空调passdef turn_off(self):# 实现关闭空调passdef set_temperature(self, temp: int):# 实现设置温度pass# 实现空调相关的命令类# AirConditionerOnCommand# AirConditionerOffCommand# TemperatureUpCommand# TemperatureDownCommand练习 2实现文本编辑器的撤销功能创建一个简单的文本编辑器支持输入文本和撤销操作实例class TextEditor:def __init__(self):self.content def add_text(self, text: str):# 实现添加文本passdef delete_text(self, length: int):# 实现删除文本pass# 实现文本编辑命令# AddTextCommand# DeleteTextCommand常见问题解答Q: 命令模式适用于什么场景A:命令模式特别适合以下场景需要将操作参数化如按钮绑定不同功能需要支持撤销/重做功能需要将操作放入队列中延迟执行需要记录操作日志需要支持事务操作Q: 命令模式的缺点是什么A:主要缺点包括可能会创建大量的命令类增加了代码的复杂度对于简单操作可能显得过于繁琐Q: 如何选择是否使用命令模式A:考虑以下几点如果只需要简单的方法调用不要使用命令模式如果需要撤销/重做功能强烈推荐使用如果系统需要高度解耦命令模式是很好的选择如果操作需要排队或日志记录命令模式很合适总结命令模式通过将操作封装成对象实现了调用者与接收者的解耦提供了强大的扩展能力。虽然会增加一些代码复杂度但在需要撤销/重做、操作队列、日志记录等场景下命令模式是不可或缺的设计模式。关键要点命令模式将做什么和谁来做分离支持撤销、重做、队列等高级功能易于扩展新的命令在 GUI 应用、事务系统、游戏开发中广泛应用❤️❤️❤️本人水平有限如有纰漏欢迎各位大佬评论批评指正如果觉得这篇文对你有帮助的话也请给个点赞、收藏下吧非常感谢! Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧

相关新闻