# Mediator

> Instead of components talking directly to each other and creating a dependency web, they all talk through a Mediator — one place owns all the communication logic.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/mediator/

---

## Description
**Intent**: Reduce the spaghetti of direct component-to-component dependencies by centralizing communication through a single mediator.

**Context**: You have a UI with a form, several input fields, dropdowns, and buttons that all need to react to each other. Or a chat room where participants need to broadcast messages. Components are tightly coupled — changing one requires updating all the others it communicates with.

**Solution**: Components don't reference each other. They reference the Mediator and emit events to it. The Mediator knows who cares about what and routes accordingly. Adding a new component = register it with the Mediator, touch nothing else.


## Use Cases
Use for complex UI components that react to each other, chat/messaging systems, air traffic control-style coordination problems, or any system where N components all need to communicate.



## Implementation Example

```javascript
class Mediator {
  notify(sender, event) {}
}

class ConcreteMediator extends Mediator {
  constructor(c1, c2) {
    super();
    this.c1 = c1;
    this.c1.setMediator(this);
    this.c2 = c2;
    this.c2.setMediator(this);
  }
  notify(sender, event) {
    if (event === 'A') {
      console.log("Mediator reacts on A and triggers following operations:");
      this.c2.doD();
    }
  }
}

```



## Trade-offs


### Advantages

- Each component only knows about the Mediator — zero cross-component coupling.

- Add new components or change communication logic in one place.




### Considerations & Drawbacks

- The Mediator is a God Object waiting to happen — it absorbs complexity from all sides and can become unmaintainable.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/mediator)

