Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Mediator

Central object coordinates colleagues to reduce coupling.

C#

// Mediator
class Chat
{
	private readonly List _users = new();
	public void Join(User u) { _users.Add(u); u.Mediator = this; }
	public void Send(string msg, User from)
	{
		foreach (var u in _users.Where(x => x != from))
			u.Receive(msg, from);
	}
}

// Colleague
class User
{
	public string Name { get; }
	public Chat? Mediator { get; set; }
	public User(string name) => Name = name;
	public void Send(string msg) => Mediator?.Send(msg, this);
	public void Receive(string msg, User from) => Console.WriteLine($"{Name} <- {from.Name}: {msg}");
}

var chat = new Chat();
var a = new User("A");
var b = new User("B");
chat.Join(a);
chat.Join(b);
a.Send("hi");
next