命令设计模式

官方定义:命令模式是一种行为设计模式, 它可将请求转换为一个包含与请求相关的所有信息的独立对象。 该转换让你能根据不同的请求将方法参数化、 延迟请求执行或将其放入队列中, 且能实现可撤销操作。

核心:将函数封装为对象。

封装后请求就可以存储。

实际看来,命令模式在代码实现中,对于函数式编程语言,类似与回调函数传参,对于非函数式编程语言,由于无法将函数作为参数传递,将函数封装为一个对象的方法,传递对象来实现传递不同的命令。

按照代码的实现形式,和策略模式类似,但是策略模式是不同算法的实现相同的目的,一般拿冒泡排序,归并排序,选择排序来类比,

实现来看,每个命令都得写个类,感觉无限增加了代码的膨胀度,目前没体会到该模式的优势,本可以只需简单写个方法实现相同的功能。

应用场景:目前没啥感受,纯粹只是学习。

 按照标准模式写的命令模式样例:

import abc


class Command(metaclass=abc.ABCMeta):
    def pressed(self):
        pass


class Recevier(metaclass=abc.ABCMeta):
    def lighton(self):
        pass

    def light_off(self):
        pass


class LightRecevier(Recevier):
    def lighton(self):
        print("请求开灯")

    def light_off(self):
        print("请求关灯")


class LightOnCommand(Command):
    def __init__(self, receive):
        self.recevie = receive

    def pressed(self):
        self.recevie.lighton()


class LightOffCommand(Command):
    def __init__(self, receive):
        self.recevie = receive

    def pressed(self):
        self.recevie.light_off()


class Invoker():
    def __init__(self, command):
        self.command = command

    def excute(self):
        self.command.pressed()


if __name__ == "__main__":
    receiver = LightRecevier()
    off_command = LightOffCommand(receiver)
    invoker = Invoker(off_command)
    invoker.excute()

维基上给的,感觉又和工厂模式好像:

class Switch(object):
    """The INVOKER class"""
    def __init__(self, flip_up_cmd, flip_down_cmd):
        self.flip_up = flip_up_cmd
        self.flip_down = flip_down_cmd

class Light(object):
    """The RECEIVER class"""
    def turn_on(self):
        print("The light is on")
    def turn_off(self):
        print("The light is off")

class LightSwitch(object):
    """The CLIENT class"""
    def __init__(self):
        lamp = Light()
        self._switch = Switch(lamp.turn_on, lamp.turn_off)

    def switch(self, cmd):
        cmd = cmd.strip().upper()
        if cmd == "ON":
            self._switch.flip_up()
        elif cmd == "OFF":
            self._switch.flip_down()
        else:
            print("Argument 'ON' or 'OFF' is required.")

# Execute if this file is run as a script and not imported as a module
if __name__ == "__main__":
    light_switch = LightSwitch()
    print("Switch ON test.")
    light_switch.switch("ON")
    print("Switch OFF test.")
    light_switch.switch("OFF")
    print("Invalid Command test.")
    light_switch.switch("****")

上一篇:【JavaScript】清空数组的三种方式


下一篇:iOS flutter学习之路 day19