命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
使用场景
认为是命令的地方都可以使用命令模式
代码实现
from abc import ABCMeta, abstractmethod
"""
命令模式实现
一个遥控器
"""
class RemoteControl:
def __init__(self):
self.commands = dict()
def set_command(self, slot: str, command):
self.commands[slot] = command
def on_button_was_pressed(self, slot):
self.commands[slot].execute()
class Command(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class Light:
def __init__(self):
self.status = False
def on(self):
self.status = not self.status
print("成功开灯了" if self.status == 1 else "成功关灯了")
class LightCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.on()
class TV:
def __init__(self):
self.status = False
def on(self):
self.status = not self.status
print("成功打开电视" if self.status == 1 else "成功关闭电视")
class TVCommand(Command):
def __init__(self, tv: TV):
self.tv = tv
def execute(self):
self.tv.on()
if __name__ == '__main__':
kitchen_light = Light()
kitchen_light_command = LightCommand(kitchen_light)
tv = TV()
tv_command = TVCommand(tv)
remote_control = RemoteControl()
remote_control.set_command("kitchen_light", kitchen_light_command)
remote_control.set_command("tv", tv_command)
remote_control.on_button_was_pressed("kitchen_light")
remote_control.on_button_was_pressed("kitchen_light")
remote_control.on_button_was_pressed("tv")