python 设计模式(七) 命令模式(command pattern)

本文介绍了Python中的命令模式,通过类封装命令函数以实现调用者与接收者的解耦。内容包括命令模式的三个组成部分:命令调用者、命令和命令接收者。代码示例展示了Receiver类的start, stop, suspend, play方法,以及Start_command, Stop_command等具体命令类,最后是Client客户端如何通过command_do方法调用命令执行。" 92792533,7739177,Java TCP Socket通信教程,"['Java', '网络编程', 'TCP/IP']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

命令模式是利用类来实现对命令函数的封装,实现命令调用者和命令接收者之间的解耦,命令模式具体包括三部分:

1 命令调用者(客户端,调用命令的函数或者类)

2 命令(对命令接收者命令函数的封装)

3 命令接收者(真正执行命令的地方,实现了众多命令函数)

三者的关系如下图


具体代码实现如下

import abc


class Receiver(object):
    '''
    命令接收者,正在执行命令的地方,实现了众多命令函数
    '''
    def start(self):
        print('execute start command')

    def stop(self):
        print('execute stop command')

    def suspend(self):
        print('execute suspend command')

    def play(self):
        print('execute play command')


class Command(object):
    """
    command抽象方法,子类必须要实现execute方法
    """

    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def execute(self):
        pass


class Start_command(Command):
    """
    start命令类,对命令接收者类中start方法的封装
    """
    def __init__(self, receiver):
        self.receiver = receiver

    def execute(self):
        self.receiver.start()


class Stop_command(Command):
    """
    stop命令类,对命令接收者类中stop方法的封装
    """
    def __init__(self, receiver):
        self.receiver = receiver

    def execute(self):
        self.receiver.stop()


class Client(object):
    """
    调用命令的客户端
    """
    def __init__(self, command):
        self.command = command

    def command_do(self):
        self.command.execute()


if __name__ == '__main__':
    receiver = Receiver()
    start_command = Start_command(receiver)
    client = Client(start_command)
    client.command_do()
    # 可以直接更换命令,如下,把start命令,换成stop命令
    stop_command = Stop_command(receiver)
    client.command = stop_command
    client.command_do()

结果如下

execute start command
execute stop command

代码实现了Receiver类,命令接收者类,并实现了start,stop,suspend, play方法。他是命令真正执行的地方

command抽象类,实现了Start_command,Stop_command。

Client客户端类,实现了command_do方法。此方法调用command类的execute方法,execute方法又是对receiver类中命令函数的封装。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值