Logo

dev-resources.site

for different kinds of informations.

Mediator Pattern

Published at
1/15/2025
Categories
csharp
designpatterns
programming
microsoft
Author
stevsharp
Author
9 person written this
stevsharp
open
Mediator Pattern

Mediator Pattern in C#: A Comprehensive Guide

The Mediator Pattern is a behavioral design pattern that facilitates communication between objects by centralizing their interactions. Instead of objects referring to each other directly, they communicate via a mediator. This reduces the dependencies between interacting objects, promoting loose coupling and enhancing maintainability.

Key Concepts
Mediator: Central interface or class that handles communication between various components (colleagues).
Colleague: Objects that communicate through the mediator instead of directly interacting with each other.

How to Use the Mediator Pattern

  1. Define a Mediator Interface
    Create an interface that declares methods for communication between colleagues.

  2. Implement the Mediator
    Create a concrete class implementing the mediator interface to handle the interactions.

  3. Define Colleague Classes
    These classes interact indirectly via the mediator.

  4. Integrate with the Mediator
    The colleagues are aware of the mediator but not of each other, ensuring loose coupling.

Example in C#
Mediator Interface:

public interface IMediator
{
    void Notify(object sender, string eventType);
}
Enter fullscreen mode Exit fullscreen mode

Concrete Mediator:

public class ConcreteMediator : IMediator
{
    private ComponentA _componentA;
    private ComponentB _componentB;

    public ConcreteMediator(ComponentA componentA, ComponentB componentB)
    {
        _componentA = componentA;
        _componentA.SetMediator(this);
        _componentB = componentB;
        _componentB.SetMediator(this);
    }

    public void Notify(object sender, string eventType)
    {
        if (eventType == "EventA")
        {
            Console.WriteLine("Mediator reacts to EventA and triggers B.");
            _componentB.DoSomething();
        }
        else if (eventType == "EventB")
        {
            Console.WriteLine("Mediator reacts to EventB and triggers A.");
            _componentA.DoSomething();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Colleague Classes:

public abstract class BaseComponent
{
    protected IMediator _mediator;

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

public class ComponentA : BaseComponent
{
    public void TriggerEventA()
    {
        Console.WriteLine("ComponentA triggers EventA.");
        _mediator.Notify(this, "EventA");
    }

    public void DoSomething()
    {
        Console.WriteLine("ComponentA is doing something.");
    }
}

public class ComponentB : BaseComponent
{
    public void TriggerEventB()
    {
        Console.WriteLine("ComponentB triggers EventB.");
        _mediator.Notify(this, "EventB");
    }

    public void DoSomething()
    {
        Console.WriteLine("ComponentB is doing something.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Client Code:

var componentA = new ComponentA();
var componentB = new ComponentB();
var mediator = new ConcreteMediator(componentA, componentB);

componentA.TriggerEventA();
componentB.TriggerEventB();

Enter fullscreen mode Exit fullscreen mode

Advantages of the Mediator Pattern

  • Loose Coupling: Reduces dependencies between components, making the system easier to maintain and extend.
  • Improved Readability: Centralizes communication logic, making it easier to understand the flow of interactions.
  • Flexibility: Adding or modifying interactions only requires changes to the mediator, not individual components.
  • Enhanced Testability: Individual components can be tested independently of others.

Disadvantages of the Mediator Pattern

  • Complexity: The mediator itself can become a complex and bloated class if it handles too many interactions.
  • Single Point of Failure: If the mediator fails, it impacts the entire communication network.
  • Overhead: For simple interactions, using a mediator can add unnecessary complexity.

References

Conclusion

The Mediator Pattern is a powerful design pattern that simplifies the interactions between multiple objects by centralizing communication. It promotes loose coupling and improves maintainability, making it easier to extend and test individual components in complex systems. However, as with any pattern, careful consideration is required to avoid overcomplicating the mediator itself, which can become a bottleneck if not designed carefully.

csharp Article's
30 articles in total
Favicon
Dynamically Extracting Endpoint Names and Attributes from a Custom C# MVC API
Favicon
Integrating Azure OpenAI with .NET Applications Using Microsoft.Extensions.AI
Favicon
What is Quartz.Net and its simple implementation
Favicon
Beyond the Random Class: Cryptographic Randomness in .NET 6+
Favicon
I am a beginner in Python programming and I want to develop my skills.
Favicon
Demystifying AIContents in Microsoft.Extensions.AI
Favicon
Inter-process Communication with WitCom
Favicon
Mediator Pattern
Favicon
[WPF] Draw Tree Topology
Favicon
Game Dev Digest — Issue #264 - Game Dev Insights: AI Tools, VFX, Optimization & Tutorials
Favicon
Semantic Kernel: Crea un API para Generación de Texto con Ollama y Aspire
Favicon
Building Modern Desktop Applications with .NET 9: Features and Best Practices
Favicon
Orden en el Código .NET
Favicon
Building a Solana Wallet Backend with .NET (Part 1)
Favicon
Top 10 Programming Languages to Learn in 2025 🖥️
Favicon
ИСТОРИЯ .NET
Favicon
dotnet терминал команды
Favicon
Cqrs
Favicon
Why You Should Learn C#/.NET in 2025
Favicon
Custom Middleware Extensions in .NET Core Web API
Favicon
Qt/C++ Senior Experts Provide Customized Software Development Services
Favicon
Static Lambda in C# 12 : Performance Improvement
Favicon
Builder Pattern in C#: Practical Implementation and Examples
Favicon
WitCom: Modernizing Client-Server Communication
Favicon
Permission-Based Authentication and Authorization in .NET, via Cookies
Favicon
Simplifying CRUD Operations Using Primary Constructors for Dependency Injection with Generic Interfaces
Favicon
Entendendo Service, Repository e Controller, PT. 1
Favicon
Take your skills to the next level with these top courses on a HUGE DISCOUNT!
Favicon
Como Resolver o Erro DbUpdateConcurrencyException no Entity Framework
Favicon
Loops vs Recursividade

Featured ones: