The before code tightly couples Switch to Light, making it hard to add more devices. The after code uses the Observer pattern to let Switch notify any number of observers, improving flexibility and reducing coupling.
### Before: Objects interact directly with tight coupling
class Light:
def turn_on(self):
print("Light turned on")
class Switch:
def __init__(self, light):
self.light = light
def press(self):
self.light.turn_on()
light = Light()
switch = Switch(light)
switch.press()
### After: Using Observer pattern to decouple interaction
class Light:
def turn_on(self):
print("Light turned on")
class Switch:
def __init__(self):
self._observers = []
def register(self, observer):
self._observers.append(observer)
def press(self):
for observer in self._observers:
observer.turn_on()
light = Light()
switch = Switch()
switch.register(light)
switch.press()