Mediator Design Pattern in C#

The Mediator design pattern is a behavioral pattern that promotes loose coupling between objects by centralizing their communication through a mediator object. This pattern is useful when you have a set of objects that need to interact with each other, but you want to avoid direct connections between them. Here’s a C# example of the Mediator pattern with a use case of a chat application.

Define the Mediator interface

public interface IChatMediator
{
    void SendMessage(string message, IUser user);
    void AddUser(IUser user);
}

Create the ConcreteMediator (ChatRoom)

public class ChatRoom : IChatMediator
{
    private List<IUser> users = new List<IUser>();

    public void AddUser(IUser user)
    {
        users.Add(user);
    }

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

Define the Colleague interface (IUser)

public interface IUser
{
    void SendMessage(string message);
    void ReceiveMessage(string message);
}

Create ConcreteColleague classes (User)

public class User : IUser
{
    private IChatMediator mediator;
    public string Name { get; private set; }

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

    public void SendMessage(string message)
    {
        mediator.SendMessage(message, this);
    }

    public void ReceiveMessage(string message)
    {
        Console.WriteLine($"{Name} received: {message}");
    }
}

Use Case – Chat Application

class Program
{
    static void Main(string[] args)
    {
        IChatMediator chatRoom = new ChatRoom();

        IUser user1 = new User(chatRoom, "Alice");
        IUser user2 = new User(chatRoom, "Bob");
        IUser user3 = new User(chatRoom, "Charlie");

        chatRoom.AddUser(user1);
        chatRoom.AddUser(user2);
        chatRoom.AddUser(user3);

        user1.SendMessage("Hello, everyone!");
        user2.SendMessage("Hi, Alice!");
    }
}

In this example, we have a chat application where users (colleagues) communicate through a chat room (mediator). Users send messages to the chat room, and the chat room relays those messages to all other users. This centralizes the communication and reduces the coupling between individual users.

The Mediator pattern is beneficial when you need to manage complex relationships and interactions between objects without creating tight dependencies between them. It can help improve maintainability and scalability in systems with many interconnected components.