Problem Statement
When multiple components communicate directly with each other, the system becomes tightly coupled and complex. Changes in one component can cause ripple effects, making maintenance and scaling difficult.
This diagram shows multiple components communicating only through a central Mediator, which manages all interactions and routes messages.
### Before applying Mediator pattern (tight coupling) class ComponentA: def __init__(self, component_b): self.component_b = component_b def do_a(self): print("Component A does something") self.component_b.do_b() class ComponentB: def do_b(self): print("Component B does something") # Usage b = ComponentB() a = ComponentA(b) a.do_a() ### After applying Mediator pattern (decoupled 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 == "A_done": self.component_b.do_b() class ComponentA: def __init__(self, mediator): self.mediator = mediator def do_a(self): print("Component A does something") self.mediator.notify(self, "A_done") class ComponentB: def __init__(self, mediator): self.mediator = mediator def do_b(self): print("Component B does something") # Usage mediator = Mediator() mediator.component_a.do_a()