چیست؟
پترن Mediator کلاف درهم ارجاعهای شیءبهشیء را با یک مرکز واحد عوض میکند. هر Colleague فقط Mediator را میشناسد. وقتی چیزی میخواهد، از Mediator میپرسد و Mediator تصمیم میگیرد چه کس دیگری باید باخبر شود.
یک فرودگاه را تصور کن. خلبانها برای اینکه سر نوبت فرود به توافق برسند با هم بیسیم نمیزنند؛ همه با برج مراقبت حرف میزنند. قانون مشترک (هر بار فقط یک هواپیما روی باند) دست برج است و برج به بقیه میگوید منتظر بمانند. اگر هواپیمای پنجمی اضافه شود، برای چهار هواپیمای دیگر هیچ چیزی عوض نمیشود.
در Unity این پترن به شکل یک MonoBehaviour به نام ControlTower دیده میشود که componentهای Aircraft در OnEnable خودشان را در آن ثبت میکنند. هواپیماها tower.RequestLanding(this) را صدا میزنند. برج اجازه میدهد یا رد میکند و وضعیت باند را برای بقیهٔ ناوگان اعلام میکند.
کِی به کار میآید؟
وقتی گروهی از اشیا به شکل چندبهچند با هم تعامل دارند و سیمکشی بینشان از کنترل خارج شده، سراغش برو. مثلاً پنلهای UI که همدیگر را فعال و غیرفعال میکنند، AI یک جوخه که هدفها را هماهنگ میکند، یا قطعههای پازل که به هم واکنش نشان میدهند.
جای خوبی برای قانونهای مشترکی است که مال هیچکدام از شرکتکنندهها نیستند، مثل «فقط یک در میتواند باز باشد» یا «فقط یک واحد میتواند به این هدف حمله کند».
اگر ارتباط واقعاً یکبهچند است و منطق هماهنگی ندارد، سراغش نرو؛ یک event ساده (Observer) سادهتر است. حواست هم باشد Mediator به یک god object تبدیل نشود که بیش از حد میداند.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
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();
}
}
}
}namespace Patterns.Behavioral.Mediator
{
/// <summary>
/// The mediator contract. Aircraft only ever see this interface,
/// never each other.
/// </summary>
public interface IAirTrafficMediator
{
void Register(Aircraft aircraft);
void Unregister(Aircraft aircraft);
/// <summary>Asks for the runway. Returns true if landing is cleared.</summary>
bool RequestLanding(Aircraft aircraft);
/// <summary>Called by the aircraft once it has vacated the runway.</summary>
void ReportRunwayClear(Aircraft aircraft);
}
}using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Behavioral.Mediator
{
/// <summary>
/// Concrete mediator. Owns the shared runway rule and relays
/// status messages to every other registered aircraft.
/// </summary>
public class ControlTower : MonoBehaviour, IAirTrafficMediator
{
private readonly List<Aircraft> fleet = new();
private Aircraft onRunway;
public void Register(Aircraft aircraft)
{
if (!fleet.Contains(aircraft))
fleet.Add(aircraft);
}
public void Unregister(Aircraft aircraft)
{
fleet.Remove(aircraft);
if (onRunway == aircraft)
onRunway = null;
}
public bool RequestLanding(Aircraft aircraft)
{
if (onRunway != null)
{
Debug.Log($"Tower: {aircraft.CallSign}, hold. Runway occupied by {onRunway.CallSign}.");
return false;
}
onRunway = aircraft;
Broadcast(aircraft, $"{aircraft.CallSign} is landing. Hold your position.");
return true;
}
public void ReportRunwayClear(Aircraft aircraft)
{
if (onRunway != aircraft) return;
onRunway = null;
Broadcast(aircraft, "Runway is clear.");
}
private void Broadcast(Aircraft sender, string message)
{
foreach (Aircraft other in fleet)
{
if (other != sender)
other.Receive(message);
}
}
}
}using System.Collections;
using UnityEngine;
namespace Patterns.Behavioral.Mediator
{
/// <summary>
/// Colleague. Knows the tower, never another aircraft.
/// </summary>
public class Aircraft : MonoBehaviour
{
[SerializeField] private string callSign = "UA-101";
[SerializeField] private ControlTower tower;
[SerializeField] private float landingDuration = 3f;
public string CallSign => callSign;
public bool IsLanding { get; private set; }
private IAirTrafficMediator Mediator => tower;
private void OnEnable() => Mediator.Register(this);
private void OnDisable() => Mediator.Unregister(this);
public void TryLand()
{
if (IsLanding) return;
if (Mediator.RequestLanding(this))
StartCoroutine(LandRoutine());
}
public void Receive(string message)
{
Debug.Log($"{callSign} hears tower: {message}");
}
private IEnumerator LandRoutine()
{
IsLanding = true;
yield return new WaitForSeconds(landingDuration);
IsLanding = false;
Mediator.ReportRunwayClear(this);
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: هواپیماهایی که قبل از فرود همهٔ هواپیماهای دیگر را چک میکنند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
هر Aircraft یک آرایهٔ otherAircraft دارد که در Inspector پر شده. قبل از فرود روی همهشان میچرخد تا IsLanding را چک کند، بعد روی تکتکشان Receive را صدا میزند تا خبر بدهد.
با پنج هواپیما یعنی بیست ارجاع که باید دستی هماهنگ بمانند، و کافی است یکی جا بیفتد تا هواپیمایی روی باند اشغال فرود بیاید. قانون باند در همهٔ هواپیماها کپی شده، پس یک باند دوم یا اولویت برای فرود اضطراری یعنی عوض کردن همهٔ هواپیماها با هم.
✓ چه چیزی عوض شد؟
- بهجای آرایهٔ
otherAircraftحالا یک ارجاعtowerهست که فقط از طریقIAirTrafficMediatorدیده میشود. - متد
TryLandبهجای چرخیدن روی بقیهٔ هواپیماهاMediator.RequestLanding(this)را صدا میزند؛ قانون باند اشغال حالا درControlTowerاست. - هواپیماها در
OnEnableباRegisterثبت میشوند و درOnDisableباUnregisterخارج میشوند؛ پس اضافه یا حذف کردن یکی به بقیه دست نمیزند. - حالا
LandRoutineبا صدا زدنMediator.ReportRunwayClear(this)تمام میشود و برج تصمیم میگیرد چه کسی این پیام همگانی را بشنود.
using System.Collections;
using UnityEngine;
namespace Patterns.Behavioral.Mediator
{
/// <summary>
/// Without Mediator: every aircraft holds references to every other
/// aircraft and enforces the runway rule by itself.
/// </summary>
public class Aircraft : MonoBehaviour
{
[SerializeField] private string callSign = "UA-101";
[SerializeField] private Aircraft[] otherAircraft; // wired by hand on every plane
[SerializeField] private float landingDuration = 3f;
public string CallSign => callSign;
public bool IsLanding { get; private set; }
public void TryLand()
{
if (IsLanding) return;
foreach (Aircraft other in otherAircraft)
{
if (other != null && other.IsLanding)
{
Debug.Log($"{callSign}: holding, {other.CallSign} is on the runway.");
return;
}
}
foreach (Aircraft other in otherAircraft)
other.Receive($"{callSign} is landing. Hold your position.");
StartCoroutine(LandRoutine());
}
public void Receive(string message)
{
Debug.Log($"{callSign} hears: {message}");
}
private IEnumerator LandRoutine()
{
IsLanding = true;
yield return new WaitForSeconds(landingDuration);
IsLanding = false;
foreach (Aircraft other in otherAircraft)
other.Receive("Runway is clear.");
}
}
}using System.Collections;
using UnityEngine;
namespace Patterns.Behavioral.Mediator
{
/// <summary>
/// With Mediator: the aircraft only knows the tower. The runway rule
/// and the radio broadcast live in one place.
/// </summary>
public class Aircraft : MonoBehaviour
{
[SerializeField] private string callSign = "UA-101";
[SerializeField] private ControlTower tower;
[SerializeField] private float landingDuration = 3f;
public string CallSign => callSign;
public bool IsLanding { get; private set; }
private IAirTrafficMediator Mediator => tower;
private void OnEnable() => Mediator.Register(this);
private void OnDisable() => Mediator.Unregister(this);
public void TryLand()
{
if (IsLanding) return;
if (Mediator.RequestLanding(this))
StartCoroutine(LandRoutine());
}
public void Receive(string message)
{
Debug.Log($"{callSign} hears: {message}");
}
private IEnumerator LandRoutine()
{
IsLanding = true;
yield return new WaitForSeconds(landingDuration);
IsLanding = false;
Mediator.ReportRunwayClear(this);
}
}
}مزایا و معایب
+ مزایا
- Colleagueها به هم وابسته نیستند؛ میتوانی یکی را اضافه یا حذف کنی، بدون اینکه به بقیه دست بزنی.
- قانونهای تعامل یکجا هستند، پس پیدا کردن، تغییر دادن و تست کردنشان راحت است.
- یک شبکهٔ N×N از ارجاعها به N اتصال به یک مرکز واحد تبدیل میشود.
− معایب
- Mediator ممکن است به یک god class تبدیل شود که نگهداریاش سخت است.
- همه چیز از یک شیء رد میشود، پس یک باگ در آن روی همهٔ شرکتکنندهها اثر میگذارد.
- این واسطهگری باعث میشود با یک نگاه معلوم نباشد یک فراخوانی در نهایت روی کدام اشیا اثر میگذارد.
چند نکتهٔ کاربردی
- ۰۱یک interface به نام
IMediatorتعریف کن تا بتوانی Colleagueها را با یک Mediator ساختگی تست کنی. - ۰۲Colleagueها را در
OnEnable/OnDisableثبت و از ثبت خارج کن، درست مثل اشتراک در eventها. - ۰۳اگر یک Mediator بیش از حد بزرگ شد، آن را بر اساس مسئولیت تقسیم کن (مثلاً
RunwayControllerوRadioChannel). نگذار Colleagueها دوباره مستقیم با هم حرف بزنند. - ۰۴Mediator و Observer خوب با هم جور میشوند: Mediator میتواند در درون خودش eventهای C# راه بیندازد و همچنان صاحب قانونهای هماهنگی بماند.
- ۰۵برای فراخوانیهای Colleague به Mediator از اسمهایی استفاده کن که نیت را نشان بدهند (
RequestLanding،ReportRunwayClear)، نه یکSend(string)کلی. اینطوری کامپایلر هم کمکت میکند.