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.
Jump into concepts and practice - no test required
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()
Mediator pattern in system design?notify(Component sender, String event). Others lack sender info or use incorrect method names.class Mediator {
notify(sender, event) {
if (event === 'A') return 'Handled A';
if (event === 'B') return 'Handled B';
return 'Unknown event';
}
}
const mediator = new Mediator();
console.log(mediator.notify('Component1', 'B'));mediator.notify('Component1', 'B'), so it matches the second condition and returns 'Handled B'.class Mediator {
notify(sender, event) {
if (event === 'start') {
sender.start();
} else if (event === 'stop') {
sender.stop();
}
}
}
class Component {
start() { console.log('Started'); }
stop() { console.log('Stopped'); }
}
const mediator = new Mediator();
const comp = new Component();
mediator.notify(comp, 'start');start() or stop() directly on the sender component.