vendredi 21 juillet 2023

How do I decouple lamp from button using the dependency inversion principle?

As per figure 5 in DIP I wrote the following code. How do I write it to conform to figure 6 in the same document?

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"

I am thinking of using the bridge pattern, but I am not sure how to write it.

Aucun commentaire:

Enregistrer un commentaire