In this lesson, you will learn how to reduce messy "spaghetti" dependencies between objects by using a central traffic controller called a Mediator.
The Problem: The "Many-to-Many" Web
Imagine you are building a dashboard. You have a UserList, a ChatWindow, and a NotificationBar. If the UserList needs to tell the ChatWindow to open when a user is clicked, and the ChatWindow needs to tell the NotificationBar to show a message, your classes end up holding references to each other. This is "tight coupling"—if you change one, you break the others.
The Solution: The Mediator Pattern
Instead of components talking directly to each other, they talk to a Mediator. A component doesn't need to know who else is listening; it just sends a message to the Mediator, and the Mediator decides where that information should go.
Here is a simplified look at how this works:
public interface IMediator {
void Notify(object sender, string ev);
}
public class DashboardMediator : IMediator {
private UserList _users;
private ChatWindow _chat;
public void Notify(object sender, string ev) {
if (ev == "UserSelected") {
_chat.Open(); // The Mediator handles the logic
}
}
}
By routing all interactions through the DashboardMediator, your UserList component remains completely unaware that the ChatWindow even exists. It only knows about the IMediator interface.
Why Use This?
- Reduced Coupling: Components are easier to swap or test because they aren't "tangled" with other specific classes.
- Centralized Logic: The "rules" of how your components interact live in one place, rather than being scattered across your codebase.
- Simplicity: Your components become specialists in their own jobs, rather than managing the behavior of their neighbors.
Think of the Mediator as a flight control tower. Pilots don’t talk to every other plane in the sky to coordinate landings; they talk to the tower, and the tower ensures everyone knows where to go.
Key Takeaway: The Mediator pattern replaces direct, complex dependencies between objects with a central hub, allowing your components to communicate without needing to know about each other.