Python设计模式之命令模式原理与用法实例分析

yizhihongxing

Python设计模式之命令模式原理与用法实例分析

什么是命令模式

命令模式是一种行为型设计模式,它允许将请求封装成一个对象,从而使您可以将不同的请求、队列或日志请求参数化,支持可撤销操作。

在命令模式中,有四个基本角色:

  1. Command(命令):抽象命令类,声明了执行操作的接口。
  2. ConcreteCommand(具体命令):将一个接收者对象和一个动作绑定在一起,实现了执行操作的接口。
  3. Receiver(接收者):知道如何实施与执行一个请求相关的操作。
  4. Invoker(调用者):调用命令执行请求。

命令模式示例

示例1:智能家居控制器

现在,我们来使用命令模式编写一个智能家居控制器。

定义接收者:具体动作

from abc import ABC, abstractmethod

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

    def off(self):
        print("The light is off")

定义命令接口

class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

定义具体命令

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

    def execute(self):
        self._light.on()

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

    def execute(self):
        self._light.off()

实现调用者

class RemoteControl:
    def __init__(self):
        self._on_commands = []
        self._off_commands = []

    def set_command(self, command, slot):
        if slot < 0 or slot > 1:
            return
        if isinstance(command, LightOnCommand):
            self._on_commands.insert(slot, command)
        elif isinstance(command, LightOffCommand):
            self._off_commands.insert(slot, command)

    def on_button_pressed(self, slot):
        self._on_commands[slot].execute()

    def off_button_pressed(self, slot):
        self._off_commands[slot].execute()

客户端代码

if __name__ == "__main__":
    living_room_light = Light()

    living_room_light_on = LightOnCommand(living_room_light)
    living_room_light_off = LightOffCommand(living_room_light)

    remote_control = RemoteControl()
    remote_control.set_command(living_room_light_on, 0)
    remote_control.set_command(living_room_light_off, 1)

    remote_control.on_button_pressed(0)
    remote_control.off_button_pressed(1)

    remote_control.off_button_pressed(2)  # 该操作将不会执行

示例2:财务系统日志记录

现在,我们来看看一个更加实际的例子。假设我们的公司有一个财务系统,我们使用命令模式来记录正常操作和异常操作的日志。

定义接收者

class FinanceSystem:
    def pay(self, amount):
        print(f"Paid {amount}")

    def refund(self, amount):
        print(f"Refunded {amount}")

定义命令接口

class FinanceCommand(ABC):
    @abstractmethod
    def execute(self):
        pass

定义具体命令

import logging

class PayCommand(FinanceCommand):
    def __init__(self, finance_system, amount):
        self._finance_system = finance_system
        self._amount = amount

    def execute(self):
        try:
            self._finance_system.pay(self._amount)
            logging.info(f"Paid {self._amount}")
        except Exception as e:
            logging.error(str(e))

class RefundCommand(FinanceCommand):
    def __init__(self, finance_system, amount):
        self._finance_system = finance_system
        self._amount = amount

    def execute(self):
        try:
            self._finance_system.refund(self._amount)
            logging.info(f"Refunded {self._amount}")
        except Exception as e:
            logging.error(str(e))

实现调用者

class FinanceInvoker:
    def __init__(self, finance_system):
        self._finance_system = finance_system
        self._commands = []

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

    def execute(self):
        for command in self._commands:
            command.execute()

客户端代码

if __name__ == "__main__":
    finance_system = FinanceSystem()

    logging.basicConfig(filename='finance_system.log', level=logging.INFO)

    pay_command = PayCommand(finance_system, 100)
    refund_command = RefundCommand(finance_system, 50)

    finance_invoker = FinanceInvoker(finance_system)
    finance_invoker.add_command(pay_command)
    finance_invoker.add_command(refund_command)

    finance_invoker.execute()

在示例2中,我们使用了Python内置的logging库来记录日志。当捕获到异常时,我们会将错误信息记录下来。通过记录日志,我们可以更好地追踪和debug自己的代码。

结论

在以上的示例中,我们可以看到命令模式的强大。命令模式可以很容易地扩展,而不需要修改现有的代码,只需要添加新的命令即可。它还可以在系统中增加事务性操作,并支持可撤销操作。Python中,命令模式常被用于GUI程序、智能家居等方面的开发。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python设计模式之命令模式原理与用法实例分析 - Python技术站

(0)
上一篇 2023年6月7日
下一篇 2023年6月7日

相关文章

  • Redis 如何实现分布式计数器?

    以下是 Redis 如何实现分布式计数器的完整使用攻略。 Redis 分布式计数器简介 在分布式系统中,为了保证数据的一致性和正确性,需要使用分布式计数器控制并发访问。Redis 作为一种高性能的存储数据库,可以很好地实现分布式计数器。 Redis 分布式计数器的实现原理是利用 Redis 的 INCRBY 命令,该命令可以在 Redis 中对一个键值进行原…

    python 2023年5月12日
    00
  • 如何编写python的daemon程序

    下面是如何编写Python的daemon程序的完整攻略。 什么是Daemon程序? Daemon程序是在后台运行的程序,通常不接受控制台输入和输出,由系统自动启动和停止。这种程序通常是服务器程序,例如Web服务器、数据库服务器等,需要长时间运行,并能够自动恢复。 编写Python的Daemon程序 编写Python的Daemon程序,需要遵循以下步骤: 步骤…

    python 2023年5月30日
    00
  • 显示纯文本和 HTML 版本的 Python SMTP 电子邮件

    【问题标题】:Python SMTP Emails Showing Both Plain and HTML Versions显示纯文本和 HTML 版本的 Python SMTP 电子邮件 【发布时间】:2023-04-01 18:33:01 【问题描述】: 发送一封 smtp 电子邮件,当我收到电子邮件时,它会背靠背显示纯文本版本和 html 版本。这样做…

    Python开发 2023年4月8日
    00
  • 详解C语言和Python中的线程混用

    详解C语言和Python中的线程混用 在C语言和Python中,线程是一种常用的并发编程方式。本文将详细介绍如何在C语言和Python中混用线程,并提供两个示例。 C语言中的线程 在C语言中,线程是通过pthread库来实现的。以下是一个使用pthread库创建线程的示例: #include <stdio.h> #include <pthr…

    python 2023年5月15日
    00
  • python3实现单目标粒子群算法

    下面是详细讲解“Python3实现单目标粒子群算法”的完整攻略,包括算法原理、Python实现和两个示例。 算法原理 粒子群算法是一种基于群体智能的优化算法,其主要思想是通过模拟鸟群或鱼群等群体的行为,寻找最优解。在单目标粒子群算法中,每个个体用一个向量表示,通过不断更新速度和位置,寻找最优解。 单目标粒子群算法的实现过程如下: 初始化粒子群,包括每个粒子的…

    python 2023年5月14日
    00
  • 用Python写一个自动木马程序

    首先,我们需要明确一下,在未经授权情况下编写、传播木马程序是犯罪行为,严重的甚至会涉及到法律责任。因此,我们的讨论只是在技术层面上,不鼓励任何人使用这项技术进行非法活动。 一、编写自动木马程序攻略 编写一个自动木马程序,可以分为以下几个步骤: 1.选择适合的编程语言:Python等脚本语言比较适合编写简单的木马程序,因为其语言特性、模块库、开发效率都比较高。…

    python 2023年5月19日
    00
  • 对python创建及引用动态变量名的示例讲解

    当我们在编写Python程序时,有时会需要动态地创建和引用变量名。此时,我们可以使用一些特殊的方法来实现这个功能。 一、使用globals()函数动态创建变量名 globals()函数是Python内置函数之一,用来返回全局作用域中的所有变量和函数名。在操作过程中,我们可以通过给定字符串变量名的方式动态创建新的变量名。 以下是一个简单的示例: name = …

    python 2023年6月6日
    00
  • 使用python对文件中的单词进行提取的方法示例

    下面是使用Python对文件中的单词进行提取的方法示例的完整攻略。 一、读取文件内容 首先需要打开文件并读取文件内容。可以使用Python内置的open()函数来打开文件,并使用with语句保证文件在使用完毕后自动关闭。 with open(‘file.txt’, ‘r’) as f: content = f.read() 其中file.txt为要读取的文件…

    python 2023年6月5日
    00
合作推广
合作推广
分享本页
返回顶部