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

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

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类中命令函数的封装。


猜你喜欢

转载自blog.csdn.net/ruguowoshiyu/article/details/80865812
今日推荐