如何通过依赖倒置原则解耦按钮与灯?匹配DIP文档图6实现
如何通过依赖倒置原则(Dependency Inversion Principle)解耦按钮与灯?
根据DIP文档中的图5,我编写了如下代码,请问如何修改以符合该文档的图6?
class Lamp: def __init__(self): self.state = "off" def turn_on(self): self.state = "on" def turn_off(self): self.state = "off" class Button: def __init__(self, lamp): self.lamp = lamp self.state = "off" self.lamp.state = "off" def on(self): self.state = "on" self.lamp.turn_on() def off(self): self.state = "off" self.lamp.turn_off() lamp = Lamp() button = Button(lamp) assert lamp.state == "off" button.on() assert lamp.state == "on"
我考虑使用桥接模式(Bridge Pattern),但不确定如何编写实现。我尝试了以下代码,尽管断言运行正常,但仍感觉存在问题:
from abc import ABC, abstractmethod class AbstractButton(ABC): def __init__(self, button_client): self.button_client = button_client @abstractmethod def on(self): pass @abstractmethod def off(self): pass class Button(AbstractButton): def on(self): self.button_client.on() def off(self): self.button_client.off() class ButtonClient(ABC): @abstractmethod def on(self): pass @abstractmethod def off(self): pass class Lamp(ButtonClient): def __init__(self): self.state = "off" def on(self): self.state = "on" def off(self): self.state = "off" lamp = Lamp() button = Button(lamp) assert lamp.state == "off" button.on() assert lamp.state == "on" button.off() assert lamp.state == "off"
现在受Python协议及某Stack Overflow问题启发,我编写了如下更简洁的代码,实现了包含可开关(Switchable)灯设备的按钮,状态仅在灯设备中存储,且两者均可被控制,但请问这段代码是否实现了解耦?
class Switchable: def __init__(self, device): self.device = device self.device.state = 'off' def turn_on(self): self.device.state = 'on' def turn_off(self): self.device.state = 'off' class Lamp(Switchable): def __init__(self): super().__init__(self) def __str__(self): return f"Lamp {self.state}" lamp = Lamp() button = Switchable(lamp) assert str(lamp) == "Lamp off" button.turn_on() assert str(lamp) == "Lamp on" button.turn_off() assert str(lamp) == "Lamp off" lamp.turn_on() assert str(lamp) == "Lamp on" lamp.turn_off() assert str(lamp) == "Lamp off" assert button.device.state == "off"
内容的提问来源于stack exchange,提问作者progmatico
相关产品推荐
相关产品推荐

