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

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

相关推荐
明洞日记5 分钟前
【设计模式手册011】享元模式 - 共享细粒度对象的高效之道
java·设计模式·享元模式
天下无敌笨笨熊10 分钟前
ES作为向量库研究
大数据·python·elasticsearch
数据知道18 分钟前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
帅中的小灰灰25 分钟前
C++编程观察者设计模式
数据库·c++·设计模式
程序员爱钓鱼1 小时前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae
软件开发技术深度爱好者1 小时前
Python库/包/模块管理工具
开发语言·python
程序员爱钓鱼1 小时前
Python 编程实战 · 进阶与职业发展:Web 全栈(Django / FastAPI)
后端·python·trae
郝学胜-神的一滴2 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
阿波罗尼亚2 小时前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
烤汉堡2 小时前
Python入门到实战:post请求和响应
python·html