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

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

20+ LINQ Concepts with .Net Code

LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...

C# : Understanding Types of Classes

In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla...