Mediator
Defines an object that encapsulates how a set of objects interact, reducing coupling between them.
Context
You have 7 controls on a form that affect each other. Each one knows several others — N×N references.
Problem
- M:N coupling.
- Difficult to add/remove components.
Solution
Components communicate only with a central Mediator. This changes communication from N×N to N×1.
#Example in C#
public interface IDialogMediator { void Notify(object sender, string evt); }
public class LoginDialog : IDialogMediator
{
public TextBox User = new(); public TextBox Pass = new(); public Button Login = new();
public LoginDialog()
{
User.Mediator = Pass.Mediator = Login.Mediator = this;
}
public void Notify(object sender, string evt)
{
if (sender is TextBox && evt == "changed")
Login.Enabled = User.Text.Length > 0 && Pass.Text.Length >= 8;
}
}When NOT to use it
If the mediator becomes a God Object containing all the module's logic.
Tradeoffs
| Pro | Con |
|---|---|
| Reduces coupling between components | Centralizes logic in a single point |
| Fits with MediatR / event bus | Risk of god object |
#behavioral #gof