Codacoda
Back to Academy

design patterns

Mediator

The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly and lets you vary their interaction independently. The key participants are the Mediator (defines an interface for communicating with Colleague objects), ConcreteMediator (coordinates Colleague objects and knows them all), and Colleague (each Colleague communicates with its Mediator rather than with other Colleagues directly). Think of an air traffic control tower: planes (colleagues) do not communicate with each other directly — all communication goes through the control tower (mediator), which coordinates takeoffs, landings, and routing. Use Mediator when a set of objects communicate in well-defined but complex ways, and you want to reduce the chaotic dependencies between them.

Use Cases

  • Chat room systems mediating messages between users
  • Air traffic control coordinating aircraft
  • UI dialog boxes coordinating widget interactions
  • Event bus systems in component-based architectures

Visualization

notify<<interface>>Mediator+notify(sender, event…ConcreteMediator+notify(sender, event)ColleagueA+operationA()ColleagueB+operationB()ColleagueC+operationC()
Speed:1x
Mediator — defines an object that encapsulates how colleagues interactStep 1 / 7

Implementation

Output

Click "Run Code" to see output...