Before, ComponentA directly calls ComponentB, creating tight coupling. After applying the Mediator pattern, both components communicate through the Mediator, which controls interactions and reduces dependencies.
### Before: Direct communication causing tight coupling
class ComponentA:
def __init__(self, component_b):
self.component_b = component_b
def do_action(self):
print("ComponentA does action")
self.component_b.notify()
class ComponentB:
def notify(self):
print("ComponentB notified")
b = ComponentB()
a = ComponentA(b)
a.do_action()
### After: Using Mediator pattern to centralize communication
class Mediator:
def __init__(self):
self.component_a = ComponentA(self)
self.component_b = ComponentB(self)
def notify(self, sender, event):
if sender == self.component_a and event == "action_done":
self.component_b.handle()
class ComponentA:
def __init__(self, mediator):
self.mediator = mediator
def do_action(self):
print("ComponentA does action")
self.mediator.notify(self, "action_done")
class ComponentB:
def __init__(self, mediator):
self.mediator = mediator
def handle(self):
print("ComponentB handles event")
mediator = Mediator()
mediator.component_a.do_action()