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.

microsoft Article's
30 articles in total
Favicon
Announcing Powerful Devs Conference + Hack Together 2025
Favicon
What is Cloud Service Providers? Types, Benefits, & Examples
Favicon
Самые необычные технологические новинки, представленные на CES 2025
Favicon
Microsoft Security: A Comprehensive Approach to Digital Protection
Favicon
How do I track my parcel in professional courier?
Favicon
Panic Button: My SharePoint File Vanished (But Don't Worry, It's Not Gone Forever)
Favicon
Microsoft Project in 2025
Favicon
NET9: Swagger no compatible
Favicon
Cybersecurity for Beginners: Your Guide to Getting Started
Favicon
NET9: Swagger no compatible [Alternativas]
Favicon
PlayStation или Xbox: а нужен ли вообще отдельный девайс для игр в 2023?
Favicon
A tutorial on WinUI 3 (2025)
Favicon
Fixing Linux Backup Sync Issues for exFAT Compatibility
Favicon
Mediator Pattern
Favicon
Exploring the Potential of Generative AI and Microsoft Dynamics 365 Business Central
Favicon
My Favorite Tech Stack for Startup Success in 2025
Favicon
Phi-4: Microsoft’s Compact AI Redefining Performance and Efficiency
Favicon
The Role of Azure AI in Business: Transforming Enterprises with Intelligent Solutions in 2025
Favicon
10 Essential Tools Every Azure Administrator Should Know in 2025
Favicon
Managing Relationships, Migrations, and Performance Optimization in ASP.NET Core MVC
Favicon
Introduction to Microsoft Entra ID
Favicon
Beyond Traditional Development: Power Apps and The New Era of Business Agility
Favicon
Unlock Free Microsoft Resources to Supercharge Your Tech Journey 🚀
Favicon
Free Azure 100$ Credits
Favicon
Microsoft выпустила обновленную малую языковую модель Phi-4
Favicon
Mastering Azure Identity with Microsoft Azure: A Guide for Beginners
Favicon
Top Cybersecurity Trends for 2025 and How to Stay Ahead
Favicon
CREATING EC2 INSTANCE ON AWS AND INSTALLING IIS SERVER.
Favicon
How Microsoft for Startups Boosts Entrepreneurial Success
Favicon
Which is the Best Microsoft Azure Institute in Bangalore?

Featured ones: