Junior — Middle
Can you explain what the Mediator pattern is and its main idea?
sobes.tech AI
Answer from AI
The Mediator pattern is designed to simplify interactions between objects by reducing the number of direct connections between them. Instead of objects communicating directly with each other, they interact through a mediator. This reduces component coupling and makes the code easier to maintain and extend.
Main idea:
- All interactions between components go through a single object — the mediator.
- Components do not know about other components directly, only about the mediator.
- The mediator manages communication and coordination between objects.
Example in C#:
// Mediator interface
public interface IMediator
{
void Notify(object sender, string ev);
}
// Concrete mediator
public class ConcreteMediator : IMediator
{
private Component1 _component1;
private Component2 _component2;
public ConcreteMediator(Component1 c1, Component2 c2)
{
_component1 = c1;
_component1.SetMediator(this);
_component2 = c2;
_component2.SetMediator(this);
}
public void Notify(object sender, string ev)
{
if (ev == "A")
{
Console.WriteLine("Mediator reacts on A and triggers following operations:");
_component2.DoC();
}
else if (ev == "D")
{
Console.WriteLine("Mediator reacts on D and triggers following operations:");
_component1.DoB();
_component2.DoC();
}
}
}
// Base component
public class BaseComponent
{
protected IMediator _mediator;
public BaseComponent(IMediator mediator = null)
{
_mediator = mediator;
}
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
}
public class Component1 : BaseComponent
{
public void DoA()
{
Console.WriteLine("Component 1 does A.");
_mediator.Notify(this, "A");
}
public void DoB()
{
Console.WriteLine("Component 1 does B.");
}
}
public class Component2 : BaseComponent
{
public void DoC()
{
Console.WriteLine("Component 2 does C.");
}
public void DoD()
{
Console.WriteLine("Component 2 does D.");
_mediator.Notify(this, "D");
}
}