Skip to content

Mediator

A pattern that collects interactions between many objects into a mediator so direct dependencies between objects are reduced.

  • When centrally controlling inventory, equipment, and shop UI interactions.
  • When mutual references start becoming too complex.
  • Mediator
  • Concrete Mediator
  • Colleague

The code below is a simplified Unity example based on the scenario described above.

public interface IUiMediator
{
void Notify(object sender, string eventId);
}
public sealed class LobbyUiMediator : IUiMediator
{
public InventoryPanel InventoryPanel { get; set; }
public EquipmentPanel EquipmentPanel { get; set; }
public void Notify(object sender, string eventId)
{
if (sender == InventoryPanel && eventId == "ItemSelected")
{
EquipmentPanel.PreviewSelectedItem();
}
}
}
  • Behavior is separated into smaller units, which reduces the impact of changes.
  • Adding or swapping rules is relatively safe.
  • As the number of objects and indirect calls increases, the flow can become harder to follow.
  • Ordering bugs should be pinned down with tests.

This shows the flow where a mediator routes communication instead of components talking directly.

Mediator Flow