Skip to main content

Understanding the Mediator Design Pattern in C#

 

The Mediator design pattern is a behavioral pattern that defines an object (mediator) that encapsulates how a set of objects interact. By centralizing the communication between objects, the Mediator pattern reduces the dependencies between them, promoting loose coupling.

Understanding the State Design Pattern in C#

Example Without Mediator Pattern

Let's consider a scenario where we have a chat application with multiple users. Each user can send and receive messages. Instead of having users communicate directly with each other, we'll use a ChatRoom mediator to handle all interactions.
using System;
using System.Collections.Generic;

namespace WithoutMediatorPattern
{
    // User class
    class User
    {
        public string Name { get; private set; }
        private List<User> _contacts = new List<User>();

        public User(string name)
        {
            Name = name;
        }

        public void AddContact(User user)
        {
            _contacts.Add(user);
        }

        public void SendMessage(string message)
        {
            foreach (var contact in _contacts)
            {
                contact.ReceiveMessage(message, this);
            }
        }

        public void ReceiveMessage(string message, User sender)
        {
            if (sender != this)
            {
                Console.WriteLine($"{Name} received: {message}");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create users
            User alice = new User("Alice");
            User bob = new User("Bob");
            User charlie = new User("Charlie");

            // Add contacts
            alice.AddContact(bob);
            alice.AddContact(charlie);
            bob.AddContact(alice);
            bob.AddContact(charlie);
            charlie.AddContact(alice);
            charlie.AddContact(bob);

            // Send messages
            alice.SendMessage("Hello everyone!");
            bob.SendMessage("Hi Alice!");
        }
    }
}

Problems with This Approach

  1. Tight Coupling: Each User has a list of contacts and is responsible for sending messages to them. This creates tight coupling between users, as each user needs to manage its own list of contacts.

  2. Code Duplication: The logic for sending and receiving messages is embedded within the User class. If the message handling logic needs to change (e.g., adding new features or modifying the existing behavior), it has to be updated across multiple parts of the codebase.

  3. Scalability Issues: As the number of users increases, managing direct interactions between users can become cumbersome and error-prone. Each user must manually add all their contacts, and maintaining this list becomes increasingly complex.

  4. Lack of Centralized Control: There is no single point of control for message handling and routing. Each user is responsible for handling communication, which can lead to inconsistent behavior and difficulty in managing interactions.

How the Mediator Pattern Solves These Problems

  1. Decoupling: The Mediator pattern introduces a mediator (the ChatRoom), which handles all communication between users. This decouples the users from each other, allowing them to focus solely on sending and receiving messages through the mediator.

  2. Single Responsibility: The ChatRoom class takes on the responsibility of managing user interactions and message routing. This centralization makes it easier to manage and update the communication logic without affecting the User class.

  3. Improved Scalability: Adding or removing users, or modifying how messages are routed, becomes easier because all communication logic is contained within the ChatRoom. Users only need to interact with the mediator, not each other.

  4. Centralized Control: The ChatRoom provides a single point of control for managing message sending and receiving. This centralized control ensures consistent behavior and simplifies management of user interactions.

Revisited Code with Command Pattern

Here is how we can implement this pattern :
using System;
using System.Collections.Generic;

namespace MediatorPattern
{
    // Mediator interface
    interface IChatRoom
    {
        void SendMessage(string message, User user);
        void AddUser(User user);
    }

    // Concrete mediator
    class ChatRoom : IChatRoom
    {
        private readonly List<User> _users = new List<User>();

        public void AddUser(User user)
        {
            _users.Add(user);
            user.SetChatRoom(this);
        }

        public void SendMessage(string message, User sender)
        {
            foreach (var user in _users)
            {
                // Message should not be sent to the sender
                if (user != sender)
                {
                    user.ReceiveMessage(message);
                }
            }
        }
    }

    // Colleague class
    abstract class User
    {
        protected IChatRoom _chatRoom;
        public string Name { get; private set; }

        protected User(string name)
        {
            Name = name;
        }

        public void SetChatRoom(IChatRoom chatRoom)
        {
            _chatRoom = chatRoom;
        }

        public abstract void ReceiveMessage(string message);

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

    // Concrete colleague
    class ConcreteUser : User
    {
        public ConcreteUser(string name) : base(name) { }

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

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

            User alice = new ConcreteUser("Alice");
            User bob = new ConcreteUser("Bob");
            User charlie = new ConcreteUser("Charlie");

            chatRoom.AddUser(alice);
            chatRoom.AddUser(bob);
            chatRoom.AddUser(charlie);

            alice.SendMessage("Hello everyone!");
            bob.SendMessage("Hi Alice!");
        }
    }
}

Why Can't We Use Other Design Patterns Instead?

  • Observer Pattern: The Observer pattern defines a one-to-many dependency where one object (subject) notifies its dependents (observers) of changes. It does not centralize communication and interactions.
  • Command Pattern: The Command pattern encapsulates requests as objects and does not focus on centralizing interactions between multiple objects.
  • Chain of Responsibility Pattern: The Chain of Responsibility pattern passes requests along a chain of handlers. It is not designed for centralizing interactions but rather for processing requests through a series of handlers.

Steps to Identify Use Cases for the Mediator Pattern

  1. Complex Interactions: Identify scenarios with complex interactions between multiple objects.
  2. Reduce Dependencies: Look for cases where reducing direct dependencies between objects would simplify the system.
  3. Centralize Control: Consider the Mediator pattern when you need a single point of control for managing interactions.
  4. Encapsulation of Communication: Use the Mediator pattern to encapsulate and manage communication and interactions.

By following these steps and implementing the Mediator pattern, you can simplify interactions, reduce dependencies, and centralize communication management in your system, enhancing flexibility and maintainability.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...