Using the Mediator Pattern with C#: An Effective Communication Method

Using the Mediator Pattern with C#: An Effective Communication Method


The Mediator Pattern is a design pattern used in software development processes to manage the relationships between objects. Using this pattern in object-oriented programming languages such as C# makes your code more organized and maintainable. In this article, we will explain how to implement the Mediator Pattern in C#, its advantages, and illustrate with an example application.

Basic Principles of the Mediator Pattern

The Mediator Pattern enables communication through a mediator without direct interaction between the objects. This approach reduces the dependencies between objects and helps the code be more modular. Basically, it consists of three components: Mediator, Colleagues (Facilitators), and Communication Methods. Each colleague sends and receives messages through the mediator.

1. Mediator Interface

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

2. Facilitator Classes

public abstract class Colleague
{
    protected IMediator mediator;

    public Colleague(IMediator mediator)
    {
        this.mediator = mediator;
    }
}

public class ConcreteColleague1 : Colleague
{
    public ConcreteColleague1(IMediator mediator) : base(mediator) {}

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

public class ConcreteColleague2 : Colleague
{
    public ConcreteColleague2(IMediator mediator) : base(mediator) {}

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

3. Mediator Class

public class ConcreteMediator : IMediator
{
    private ConcreteColleague1 colleague1;
    private ConcreteColleague2 colleague2;

    public void Register(Colleague colleague)
    {
        if (colleague is ConcreteColleague1)
        {
            colleague1 = (ConcreteColleague1)colleague;
        }
        else if (colleague is ConcreteColleague2)
        {
            colleague2 = (ConcreteColleague2)colleague;
        }
    }

    public void Send(string message, Colleague colleague)
    {
        if (colleague == colleague1)
        {
            Console.WriteLine("Colleague1 sends: " + message);
            colleague2.Receive(message);
        }
        else
        {
            Console.WriteLine("Colleague2 sends: " + message);
            colleague1.Receive(message);
        }
    }
}

Conclusion

The Mediator Pattern is an effective tool for managing complex communications in C# projects. This pattern increases the overall flexibility of the system while supporting the independent change and evolution of objects. The example shared above provides a basic overview of how this design pattern can be implemented. By using the Mediator Pattern in your projects, you can make your code more organized and sustainable.