In this lesson, you will learn how to use the Mediator pattern to stop components from talking directly to each other, creating a central hub for all communications.
The Problem: The "Spaghetti" Web
Imagine you are building a smart home system. You have a Light, a Thermostat, and a SecurityAlarm. If the SecurityAlarm triggers, you want the Light to turn on and the Thermostat to adjust. If every class holds a reference to the others, you end up with a tangled web of dependencies. If you add a new device, you have to modify every existing class. This is hard to maintain!
The Solution: The Mediator
The Mediator pattern acts like an air traffic controller. Instead of the SecurityAlarm calling the Light directly, it simply tells the Mediator: "The alarm is triggered." The Mediator knows exactly which other components need to be notified.
Here is a simplified look at how this simplifies your code:
public class SmartHomeMediator
{
private Light _light = new();
private Thermostat _thermostat = new();
public void Notify(string eventCode)
{
if (eventCode == "AlarmTriggered")
{
_light.TurnOn();
_thermostat.SetTemperature(22);
}
}
}
Why This Matters
By funneling communications through a single class, your components become decoupled. The SecurityAlarm doesn't need to know that a Light or a Thermostat even exists. It only knows about the Mediator.
This makes your code much easier to test and modify. If you decide to add a SoundSystem that plays a siren, you only update the Mediator. You don't have to touch the SecurityAlarm code at all. You’ve effectively flattened an complex graph of dependencies into a clean, star-shaped topology where everything flows through the center.
Key Takeaway: The Mediator pattern prevents "spaghetti dependencies" by ensuring components communicate through a single, central hub rather than interacting with each other directly.