Chuyển tới nội dung chính

Mediator Pattern (Mẫu Mediator)

Định nghĩa (Definition)

Mediator định nghĩa một object đóng gói cách một tập object tương tác (Encapsulates How Objects Interact). Mediator thúc đẩy loose coupling bằng cách giữ object không tham chiếu trực tiếp đến nhau, để mediator điều phối tương tác.

Ví dụ Coffee Shop

Trong ca làm việc bận rộn, barista, thu ngân (Cashier), bếp (Kitchen), và người giao hàng (Delivery) đều cần giao tiếp. Thay vì mỗi component biết về mọi component khác, chúng giao tiếp qua CoffeeShopMediator — trung tâm điều phối.

Cấu trúc (Structure)

Concrete Mediator

public class CoffeeShopMediator : ICoffeeShopMediator
{
private CashierComponent? _cashier;
private BaristaComponent? _barista;
private KitchenComponent? _kitchen;
private DeliveryComponent? _delivery;

public void Register(CashierComponent c) => _cashier = c;
public void Register(BaristaComponent b) => _barista = b;
public void Register(KitchenComponent k) => _kitchen = k;
public void Register(DeliveryComponent d) => _delivery = d;

public void Notify(string sender, string @event, string data)
{
switch (@event)
{
case "OrderPlaced":
var parts = data.Split(':');
_cashier?.ProcessPayment(parts[0], 4.50m);
_barista?.Brew(parts[1]);
break;
case "CoffeeReady":
_delivery?.Deliver(data);
break;
}
}
}

Client

var mediator = new CoffeeShopMediator();
var cashier = new CashierComponent(mediator);
var barista = new BaristaComponent(mediator);
mediator.Register(cashier);
mediator.Register(barista);

cashier.TakeOrder("Alice", "Latte");
// [Thu ngân] Alice đặt Latte
// [Thu ngân] Đã thanh toán
// [Barista] Đang pha Latte...
// [Giao hàng] Giao: Latte
mẹo

Không component nào nói chuyện trực tiếp với component khác. CashierComponent không biết về BaristaComponent. Mediator xử lý mọi điều phối.

Mediator vs Observer

MediatorObserver
Giao tiếpHai chiều (colleague ↔ mediator)Một chiều (subject → observer)
Ai biết aiMediator biết tất cả colleagueSubject không biết observer
ComplexityTập trung trong mediatorPhân tán qua observer

Sử dụng thực tế trong .NET (.NET Real-World Usage)

  • MediatR library — implementation mediator phổ biến nhất trong .NET
  • UI Dialog box — form control giao tiếp qua form mediator
  • Air traffic control — máy bay giao tiếp qua tháp, không trực tiếp
  • Chat room — user gửi message qua server, không peer-to-peer

Khi nào sử dụng (When to Use)

  • Tập object giao tiếp phức tạp nhưng có định nghĩa rõ ràng
  • Muốn tránh quan hệ many-to-many giữa component
  • Tái sử dụng component khó vì nó tham chiếu nhiều component khác

Khi nào KHÔNG sử dụng (When NOT to Use)

  • Chỉ hai component tương tác — giao tiếp trực tiếp đơn giản hơn
  • Mediator trở thành god object — tách trách nhiệm
  • Tương tác đơn giản — đừng thêm complexity

Điểm chính (Key Takeaways)

  • Mediator tập trung giao tiếp giữa colleague
  • Component chỉ biết mediator — loose coupling giữa colleague
  • Thay đổi logic tương tác nằm ở một nơi (mediator)
  • Mediator có thể trở nên phức tạp — cân nhắc tách thành nhiều mediator

Câu hỏi phỏng vấn (Interview Questions)

Q: MediatR implement Mediator pattern như thế nào? MediatR cung cấp IMediator với Send() (command/query) và Publish() (notification). Handler đăng ký qua DI. Mediator route message đến đúng handler mà sender không biết ai xử lý.

Q: Mediator khác Facade như thế nào? Facade cung cấp interface đơn giản hóa cho subsystem — một chiều. Mediator cung cấp giao tiếp hai chiều giữa colleague. Facade trừu tượng hóa complexity; Mediator tách biệt giao tiếp.