Junior — Middle
Can you explain the concept of the mediator pattern and its role in managing object interactions?
sobes.tech AI
Answer from AI
The "Mediator" pattern is used to simplify interactions between multiple objects by reducing the number of direct connections between them. Instead of objects communicating directly with each other, they interact through a centralized object — the mediator.
Role of the mediator:
- Centralizes interaction logic.
- Reduces component coupling.
- Facilitates changes in interaction without modifying the objects themselves.
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();
}
}
}
// Components
public class Component1
{
private IMediator _mediator;
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
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
{
private IMediator _mediator;
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
public void DoC()
{
Console.WriteLine("Component 2 does C.");
}
public void DoD()
{
Console.WriteLine("Component 2 does D.");
_mediator.Notify(this, "D");
}
}
Thus, the mediator manages the interaction of components, making the system more flexible and maintainable.