0
0
CsharpConceptBeginner · 4 min read

Mediator Pattern in C#: What It Is and How It Works

The Mediator pattern in C# is a design pattern that centralizes communication between multiple objects by using a mediator object to reduce direct dependencies. It helps simplify complex interactions by having objects talk only to the mediator instead of each other directly.
⚙️

How It Works

Imagine a group chat where everyone talks through a single moderator instead of messaging each other directly. The moderator listens to each person and forwards messages to the right people. This is how the Mediator pattern works in programming.

In C#, instead of objects calling each other directly, they send messages to a mediator object. The mediator then decides how to handle these messages and which objects should be notified. This reduces the tangled web of connections between objects, making the system easier to manage and change.

💻

Example

This example shows a simple chat room where users send messages through a mediator. Users don't talk directly but rely on the chat room mediator to deliver messages.

csharp
using System;
using System.Collections.Generic;

// Mediator interface
interface IChatMediator
{
    void SendMessage(string message, User user);
    void RegisterUser(User user);
}

// Concrete Mediator
class ChatRoom : IChatMediator
{
    private List<User> users = new List<User>();

    public void RegisterUser(User user)
    {
        users.Add(user);
    }

    public void SendMessage(string message, User user)
    {
        foreach (var u in users)
        {
            if (u != user)
            {
                u.Receive(message);
            }
        }
    }
}

// Colleague
abstract class User
{
    protected IChatMediator mediator;
    protected string name;

    public User(IChatMediator mediator, string name)
    {
        this.mediator = mediator;
        this.name = name;
    }

    public abstract void Send(string message);
    public abstract void Receive(string message);
}

// Concrete Colleague
class ChatUser : User
{
    public ChatUser(IChatMediator mediator, string name) : base(mediator, name) { }

    public override void Send(string message)
    {
        Console.WriteLine($"{name} sends: {message}");
        mediator.SendMessage(message, this);
    }

    public override void Receive(string message)
    {
        Console.WriteLine($"{name} receives: {message}");
    }
}

class Program
{
    static void Main()
    {
        IChatMediator chatRoom = new ChatRoom();

        User alice = new ChatUser(chatRoom, "Alice");
        User bob = new ChatUser(chatRoom, "Bob");
        User charlie = new ChatUser(chatRoom, "Charlie");

        chatRoom.RegisterUser(alice);
        chatRoom.RegisterUser(bob);
        chatRoom.RegisterUser(charlie);

        alice.Send("Hello everyone!");
        bob.Send("Hi Alice!");
    }
}
Output
Alice sends: Hello everyone! Bob receives: Hello everyone! Charlie receives: Hello everyone! Bob sends: Hi Alice! Alice receives: Hi Alice! Charlie receives: Hi Alice!
🎯

When to Use

Use the Mediator pattern when you have many objects that interact in complex ways and you want to avoid tight coupling between them. It is helpful when changes to one object would otherwise require changes to many others.

Real-world examples include chat systems, air traffic control where planes communicate through a control tower, or UI components that coordinate actions through a central controller. It makes the system easier to maintain and extend.

Key Points

  • The Mediator pattern centralizes communication between objects.
  • It reduces dependencies and simplifies object interactions.
  • Objects communicate only with the mediator, not directly with each other.
  • It improves maintainability and flexibility of complex systems.

Key Takeaways

The Mediator pattern centralizes object communication through a mediator to reduce direct dependencies.
It simplifies complex interactions by having objects talk only to the mediator.
Use it when many objects interact and you want to reduce tight coupling.
It improves code maintainability and flexibility in complex systems.