BehavioralC#verifiedVerified

Mediator Pattern in C#

Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.

How to Implement the Mediator Pattern in C#

1Step 1: Define the mediator interface

public interface IMediator
{
    void Send(string message, Colleague sender);
}

2Step 2: Colleague base class communicates via mediator

public abstract class Colleague(IMediator mediator)
{
    protected IMediator Mediator => mediator;

    public abstract void Receive(string message);
}

3Step 3: Concrete colleagues

public class UserChat(IMediator mediator, string name)
    : Colleague(mediator)
{
    public string Name => name;

    public void Send(string message) =>
        Mediator.Send(message, this);

    public override void Receive(string message) =>
        Console.WriteLine($"{Name} received: {message}");
}

4Step 4: Concrete mediator routes messages

public class ChatRoom : IMediator
{
    private readonly List<UserChat> _users = [];

    public void Register(UserChat user) => _users.Add(user);

    public void Send(string message, Colleague sender)
    {
        foreach (var user in _users)
            if (user != sender)
                user.Receive(message);
    }
}

Mediator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mediator Pattern in the Real World

An air traffic control tower is the classic example. Instead of every plane communicating directly with every other plane—a chaotic and dangerous mess—all aircraft talk only to the control tower. The tower mediates all interactions, directing each plane based on the overall picture it maintains. Planes are decoupled from each other entirely.