←All patterns
Behavioral

Mediator

Route all communication between peers through one coordinator so they never reference each other.

What Is It?

The Mediator pattern replaces a tangle of object-to-object references with a single hub. Each colleague knows only the mediator; when it wants something, it asks the mediator, and the mediator decides who else needs to hear about it.

Picture an airport. Pilots do not radio each other to negotiate who lands first — they all talk to the control tower. The tower holds the shared rule (one plane on the runway at a time) and tells everyone else to hold. Add a fifth plane and nothing changes for the other four.

In Unity this shows up as a ControlTower MonoBehaviour that Aircraft components register with in OnEnable. Aircraft call tower.RequestLanding(this); the tower grants or denies, and broadcasts runway status to the rest of the fleet.

When Is It Used?

Use it when a group of objects interact in many-to-many ways and the wiring is getting out of hand: UI panels that enable and disable each other, squad AI that coordinates targets, or puzzle pieces that react to one another.

It is a good home for shared rules that do not belong to any single participant, such as “only one door can be open” or “only one unit may attack this target”.

Avoid it when communication is genuinely one-to-many with no coordination logic — a plain event (Observer) is simpler. And watch for the mediator turning into a god object that knows too much.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Mediator Pattern
runwayfreeholding0relayed0
RWY 09CLEAR
ControlTower
IAirTrafficMediator
UA1
air
BA2
air
LH3
air
AF4
air
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ Mediator ›AirportDemo.cs
using UnityEngine;

namespace Patterns.Behavioral.Mediator
{
    /// <summary>
    /// Client: asks individual aircraft to land. All coordination
    /// happens inside the ControlTower.
    /// </summary>
    public class AirportDemo : MonoBehaviour
    {
        [SerializeField] private Aircraft[] aircraft;

        private void Update()
        {
            for (int i = 0; i < aircraft.Length && i < 9; i++)
            {
                // Keys 1..9 request landing for each plane.
                if (Input.GetKeyDown(KeyCode.Alpha1 + i))
                    aircraft[i].TryLand();
            }
        }
    }
}
4 files · namespace Patterns.Behavioral.MediatorC# · UTF-8 · LF

Before & After

Real-world smell: aircraft that check every other aircraft before landing. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Each Aircraft has an otherAircraft array wired in the Inspector. Before landing it loops over all of them to check IsLanding, then calls Receive on each one to announce itself.

With five planes that is twenty references to keep in sync by hand, and one forgotten plane can land on an occupied runway. The runway rule is copied into every aircraft, so a second runway or priority for emergencies means changing every plane at once.

✓ What changed

  • The otherAircraft array is replaced by a single tower reference, seen only through IAirTrafficMediator.
  • TryLand calls Mediator.RequestLanding(this) instead of looping over the other planes; the occupied-runway rule now lives in ControlTower.
  • Planes Register in OnEnable and Unregister in OnDisable, so adding or removing one never touches the others.
  • LandRoutine ends with Mediator.ReportRunwayClear(this), and the tower decides who hears the broadcast.
Aircraft.Before.cs → Aircraft.After.cs+11/−18
11 using System.Collections;
22 using UnityEngine;
33
44 namespace Patterns.Behavioral.Mediator
55 {
66 /// <summary>
7− /// Without Mediator: every aircraft holds references to every other
8− /// aircraft and enforces the runway rule by itself.
7+ /// With Mediator: the aircraft only knows the tower. The runway rule
8+ /// and the radio broadcast live in one place.
99 /// </summary>
1010 public class Aircraft : MonoBehaviour
1111 {
1212 [SerializeField] private string callSign = "UA-101";
13− [SerializeField] private Aircraft[] otherAircraft; // wired by hand on every plane
13+ [SerializeField] private ControlTower tower;
1414 [SerializeField] private float landingDuration = 3f;
1515
1616 public string CallSign => callSign;
1717 public bool IsLanding { get; private set; }
1818
19+ private IAirTrafficMediator Mediator => tower;
20+
21+ private void OnEnable() => Mediator.Register(this);
22+ private void OnDisable() => Mediator.Unregister(this);
23+
1924 public void TryLand()
2025 {
2126 if (IsLanding) return;
2227
23− foreach (Aircraft other in otherAircraft)
24− {
25− if (other != null && other.IsLanding)
26− {
27− Debug.Log($"{callSign}: holding, {other.CallSign} is on the runway.");
28− return;
29− }
30− }
31−
32− foreach (Aircraft other in otherAircraft)
33− other.Receive($"{callSign} is landing. Hold your position.");
34−
35− StartCoroutine(LandRoutine());
28+ if (Mediator.RequestLanding(this))
29+ StartCoroutine(LandRoutine());
3630 }
3731
3832 public void Receive(string message)
3933 {
4034 Debug.Log($"{callSign} hears: {message}");
4135 }
4236
4337 private IEnumerator LandRoutine()
4438 {
4539 IsLanding = true;
4640 yield return new WaitForSeconds(landingDuration);
4741 IsLanding = false;
4842
49− foreach (Aircraft other in otherAircraft)
50− other.Receive("Runway is clear.");
43+ Mediator.ReportRunwayClear(this);
5144 }
5245 }
5346 }

Advantages & Disadvantages

+ Advantages

  • Colleagues are decoupled from each other; you can add or remove one without touching the rest.
  • Interaction rules live in one place, so they are easy to find, change and test.
  • Turns an N×N web of references into N links to a single hub.

− Disadvantages

  • The mediator can grow into a god class that is hard to maintain.
  • Everything goes through one object, so a bug there affects every participant.
  • Indirection makes it less obvious, at a glance, which objects end up affected by a call.

Tips

  1. 01Define an IMediator interface so colleagues can be tested with a fake mediator.
  2. 02Register and unregister colleagues in OnEnable / OnDisable, just like event subscriptions.
  3. 03If one mediator becomes too large, split it by concern (e.g. RunwayController and RadioChannel) rather than letting colleagues talk directly again.
  4. 04Mediator and Observer combine well: the mediator can raise C# events internally while still owning the coordination rules.
  5. 05Keep colleague-to-mediator calls intention-revealing (RequestLanding, ReportRunwayClear) rather than a generic Send(string), so the compiler helps you.