Advanced Design Patterns in C# - The Mediator Pattern
Advanced Design Patterns in C# - The Mediator Pattern
The Mediator Pattern helps reduce the complexity of communication between multiple objects or classes.
What is the Mediator Pattern?
The Mediator Pattern is a behavioral design pattern that defines an object that encapsulates how a set of objects interact. This pattern promotes loose coupling by keeping objects from referring to each other explicitly.
When to Use the Mediator Pattern?
- When the communication logic between multiple objects is complex.
- When you want to avoid tight coupling between objects.
- When you need a central point of control for communication.
Implementing the Mediator Pattern in C#
Step 1: Define the Mediator Interface
public interface IMediator
{
void Notify(object sender, string event);
}
Step 2: Create 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 @event)
{
if (@event == "A")
{
_componentB.DoB();
}
if (@event == "B")
{
_componentA.DoA();
}
}
}
Step 3: Define Components
public class BaseComponent
{
protected IMediator _mediator;
public BaseComponent(IMediator mediator = null)
{
_mediator = mediator;
}
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
}
public class ComponentA : BaseComponent
{
public void DoA()
{
Console.WriteLine("ComponentA does A.");
_mediator.Notify(this, "A");
}
}
public class ComponentB : BaseComponent
{
public void DoB()
{
Console.WriteLine("ComponentB does B.");
_mediator.Notify(this, "B");
}
}
Step 4: Use the Mediator
class Program
{
static void Main(string[] args)
{
var componentA = new ComponentA();
var componentB = new ComponentB();
new ConcreteMediator(componentA, componentB);
componentA.DoA();
componentB.DoB();
}
}
Benefits of the Mediator Pattern
- Reduced Complexity: Centralizes communication logic.
- Loose Coupling: Components interact through the mediator, reducing dependencies.
Conclusion
The Mediator Pattern is invaluable for managing complex communication in systems, ensuring maintainability and scalability.
I hope this article helps you understand and implement the Mediator Pattern in your C# projects. Happy coding!