Mediator Pattern
The Mediator Pattern is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.
1. The Core Concept
As an application grows, the number of connections between classes can increase exponentially. If every object talks to every other object (Many-to-Many), the system becomes a tangled mess (Spaghetti Code).
- Mediator: An object that encapsulates how a set of objects interact.
- Colleagues: The objects that communicate through the mediator. They do not know about each other.
2. Analogy: Air Traffic Control
Pilots of aircraft approaching an airport do not communicate directly with each other to decide who lands first.
- Pilots (Colleagues): Communicate only with the Air Traffic Control tower.
- ATC (Mediator): Receives messages from pilots and issues commands to ensure safety.
Without the ATC, pilots would have to know the position of every other plane, which is impossible.
3. Example (TypeScript)
Let's simulate a simple dialog box with a button and a checkbox.
// The Mediator Interface
interface Mediator {
notify(sender: object, event: string): void;
}
// The Base Component
class BaseComponent {
protected mediator: Mediator;
constructor(mediator: Mediator) {
this.mediator = mediator;
}
}
// Concrete Component 1
class Button extends BaseComponent {
click() {
console.log("Button clicked.");
this.mediator.notify(this, "click");
}
}
// Concrete Component 2
class Checkbox extends BaseComponent {
check() {
console.log("Checkbox checked.");
this.mediator.notify(this, "check");
}
}
// Concrete Mediator
class AuthenticationDialog implements Mediator {
notify(sender: object, event: string): void {
if (event === "click") {
console.log("Mediator reacts to click: Validating...");
}
if (event === "check") {
console.log("Mediator reacts to check: Updating UI...");
}
}
}
4. Pros and Cons
| Pros | Cons |
|---|---|
| SRP: You can extract the communications between various components into a single place. | God Object: The mediator can evolve into a God Object that knows too much and is hard to maintain. |
| Decoupling: Components don't depend on each other, only on the mediator. | |
| Reuse: You can reuse individual components more easily because they don't depend on specific other components. |
programming/design-patterns programming/object-oriented-programming