Files
design-patterns/03-behavioral/mediator/README.md

32 lines
1.4 KiB
Markdown

# Mediator Design Pattern — Java Example
**Pattern:** Behavioral → Mediator
**Article:** https://ankurm.com/mediator-design-pattern-java/
## What this example shows
A chat room where users never talk to each other directly. `ChatMediator` declares the hub contract (`sendMessage()`/`addUser()`). `User` is a colleague — it knows only the mediator, never other users. `ChatRoom` is the concrete mediator: it holds the list of users and routes every message to everyone except the sender. `Main` adds three users and has each one broadcast a message, then prints the O(N) vs O(N²) connection-count comparison.
## How to run
```bash
javac mediator/*.java -d out/mediator
java -cp out/mediator mediator.Main
```
Requires Java 25.
## Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Implementation: Chat Room — the Mediator interface | `ChatMediator.java` |
| Implementation: Chat Room — the Colleague | `User.java` |
| Implementation: Chat Room — the Concrete Mediator | `ChatRoom.java` |
| Implementation: Chat Room — wiring it together | `Main.java` |
Note: the "Mediator in Practice: MVC and Spring Events" snippet (`ApplicationEventPublisher`/`@EventListener` example) is illustrative only — it is not part of this repository's runnable example.
Article: https://ankurm.com/mediator-design-pattern-java/
All patterns: https://ankurm.com/design-patterns-java/