Blog / Design Patterns
The Mediator Design Pattern in C# and .Net
  • Dec 31, 2020
  • 55
  • 50

The next design pattern in the Behavioral Category that I want to talk about is the Mediator Design Pattern. Let’s take a look at the definition of this pattern and how to implement it in C# and .Net.

Note: Code can be downloaded at my Github.


Advertisement
 


1. What is the Mediator Design Pattern?

If your application has complicated dependencies between objects, the Mediator Design Pattern is able to help reduce the chaos. This pattern forces all objects to collaborate via a mediator object instead of communicating with other objects.

The mediator pattern defines an object that encapsulates how a set of objects interact.

2. When to implement the Mediator Design Pattern?

The Mediator Design Pattern is used when:

  • Your classes are tightly coupled to a bunch of others that makes it’s difficult to change the classes.
  • You can’t reuse the component in different programs because it’s to dependent on other components.
  • Your application has many component subclasses just for the purpose of reusing some basic behavior in various context.

3. How to implement the Mediator Design Pattern?

Below are steps to implement the Mediator Design Pattern:

Step 1: Create a Mediator Interface

The Mediator interface declares a method used by components to notify the mediator about various events. The Mediator may react to these events and pass the execution to other components.

public interface IMediator
{
    void Notify(object sender, string ev);
}

Step 2: Create a Mediator Class

Concrete Mediators implement cooperative behavior by coordinating several components.

class ConcreteMediator : IMediator
{
    private Component1 _component1;

    private Component2 _component2;

    public ConcreteMediator(Component1 component1, Component2 component2)
    {
        this._component1 = component1;
        this._component1.SetMediator(this);
        this._component2 = component2;
        this._component2.SetMediator(this);
    }

    public void Notify(object sender, string ev)
    {
        if (ev == "A")
        {
            Console.WriteLine("Mediator reacts on A and triggers folowing operations:");
            this._component2.DoC();
        }
        if (ev == "D")
        {
            Console.WriteLine("Mediator reacts on D and triggers following operations:");
            this._component1.DoB();
            this._component2.DoC();
        }
    }
}

Step 3: Create Sample Components

The Base Component provides the basic functionality of storing a mediator's instance inside component objects.

Concrete Components implement various functionality. They don't depend on other components. They also don't depend on any concrete mediator classes.

class BaseComponent
{
    protected IMediator _mediator;

    public BaseComponent(IMediator mediator = null)
    {
        this._mediator = mediator;
    }

    public void SetMediator(IMediator mediator)
    {
        this._mediator = mediator;
    }
}

class Component1 : BaseComponent
{
    public void DoA()
    {
        Console.WriteLine("Component 1 does A.");

        this._mediator.Notify(this, "A");
    }

    public void DoB()
    {
        Console.WriteLine("Component 1 does B.");

        this._mediator.Notify(this, "B");
    }
}

class Component2 : BaseComponent
{
    public void DoC()
    {
        Console.WriteLine("Component 2 does C.");

        this._mediator.Notify(this, "C");
    }

    public void DoD()
    {
        Console.WriteLine("Component 2 does D.");

        this._mediator.Notify(this, "D");
    }
}

Done, so now we can apply the code on client:

class Program
{
    static void Main(string[] args)
    {
        // The client code.
        Component1 component1 = new Component1();
        Component2 component2 = new Component2();
        new ConcreteMediator(component1, component2);

        Console.WriteLine("Client triggets operation A.");
        component1.DoA();

        Console.WriteLine();

        Console.WriteLine("Client triggers operation D.");
        component2.DoD();
    }
}

Output:


4. Conclusion

The Mediator Design Pattern is great for your application if it has bunch of related components. I hope this article is helpful. Please let me know your thoughts in the comment section below.


There are some benefits of keeping both UI and API parts in the same place for small projects. In this article, I will explain how I did to deploy Angular Web and ASP .Net Core API in the same folder ...

Using cherry-pick to select specific commits for your Pull Request.1. Create a new branch based on the target of the Pull Requestgit branch cherry-branch origin/master2. Switch to a new branchgit chec ...

I got CORS error after publishing my API and Angular app to IIS even though CORS is enabled and the origins of the Angular app is added. Below is how I resolved this issue.Just simple, make sure you s ...

After deployment Angular and API on IIS, it's working fine unless I refresh the page. Once refreshed, the web encountered 404 error. In this article, I will explain how to resolve this.Since Angular i ...

1. The Situation:Error Message: Pulse Secure Application failed to load Java. Please install correct JRE version.Description: This issue happens when I'm using a M1 Mac with a correct version of ...

Accelerated Mobile Pages (AMP) focuses on delivering static content from publishers as quickly as possible and possibly rewards early adopters with a boost in rank. Let's see how to implement it ...

Below is how to decrypt/convert a Hex string value into text using VB.Net:Decrypting Hex string value to string in VB.Net Function HexToString(ByVal hex As String) As String Dim text As New Sy ...

After a month of publishing on Google Play, Jungle Words has made it to the Top Android Games To Try Out In April 2021. Please check it out! GameKeys.netGameKeys is a website which introduces gam ...

Centering HTML elements is an important aspect for anything involving designing with CSS. There are various methods of centering things, however, it also depends on the elements that you are working w ...