命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

使用场景

认为是命令的地方都可以使用命令模式

  1. 右键菜单
  2. 遥控器

    优点

    1、低耦合:调用者和接收者之间没有什么直接关系,二者通过命令中的execute接口联系;
    2、扩展性好:新命令很容易加入,也很容易拼出“组合命令”。

代码实现

  1. from abc import ABCMeta, abstractmethod
  2. """
  3. 命令模式实现
  4. 一个遥控器
  5. """
  6. class RemoteControl:
  7. def __init__(self):
  8. self.commands = dict()
  9. def set_command(self, slot: str, command):
  10. self.commands[slot] = command
  11. def on_button_was_pressed(self, slot):
  12. self.commands[slot].execute()
  13. class Command(metaclass=ABCMeta):
  14. @abstractmethod
  15. def execute(self):
  16. pass
  17. class Light:
  18. def __init__(self):
  19. self.status = False
  20. def on(self):
  21. self.status = not self.status
  22. print("成功开灯了" if self.status == 1 else "成功关灯了")
  23. class LightCommand(Command):
  24. def __init__(self, light: Light):
  25. self.light = light
  26. def execute(self):
  27. self.light.on()
  28. class TV:
  29. def __init__(self):
  30. self.status = False
  31. def on(self):
  32. self.status = not self.status
  33. print("成功打开电视" if self.status == 1 else "成功关闭电视")
  34. class TVCommand(Command):
  35. def __init__(self, tv: TV):
  36. self.tv = tv
  37. def execute(self):
  38. self.tv.on()
  39. if __name__ == '__main__':
  40. kitchen_light = Light()
  41. kitchen_light_command = LightCommand(kitchen_light)
  42. tv = TV()
  43. tv_command = TVCommand(tv)
  44. remote_control = RemoteControl()
  45. remote_control.set_command("kitchen_light", kitchen_light_command)
  46. remote_control.set_command("tv", tv_command)
  47. remote_control.on_button_was_pressed("kitchen_light")
  48. remote_control.on_button_was_pressed("kitchen_light")
  49. remote_control.on_button_was_pressed("tv")