The before code tightly couples the Switch to the Light's methods. The after code uses the Command pattern to encapsulate requests as objects, allowing the Switch to execute commands without knowing the details of the Light. This decouples sender and receiver and enables flexible command management.
### Before (without Command pattern):
class Light:
def turn_on(self):
print("Light is ON")
def turn_off(self):
print("Light is OFF")
class Switch:
def __init__(self, light):
self.light = light
def on(self):
self.light.turn_on()
def off(self):
self.light.turn_off()
light = Light()
switch = Switch(light)
switch.on()
switch.off()
### After (with Command pattern):
from abc import ABC, abstractmethod
class Command(ABC):
@abstractmethod
def execute(self):
pass
class Light:
def turn_on(self):
print("Light is ON")
def turn_off(self):
print("Light is OFF")
class TurnOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_on()
class TurnOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_off()
class Switch:
def __init__(self, on_command, off_command):
self.on_command = on_command
self.off_command = off_command
def on(self):
self.on_command.execute()
def off(self):
self.off_command.execute()
light = Light()
on_command = TurnOnCommand(light)
off_command = TurnOffCommand(light)
switch = Switch(on_command, off_command)
switch.on()
switch.off()