Skip to content

Instantly share code, notes, and snippets.

@mbrookson
Created June 17, 2020 19:31
Show Gist options
  • Save mbrookson/139de93f6243709e06862e444714b4bd to your computer and use it in GitHub Desktop.
Save mbrookson/139de93f6243709e06862e444714b4bd to your computer and use it in GitHub Desktop.
Mediator example
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class Person
{
public string Name { get; }
public Person(string name)
{
Name = name;
}
public void Notify(string message)
{
Console.WriteLine(message);
}
}
// Mediator class repsonsible for sending messages and notifying participants
public class ChatRoom
{
private IList<Person> _participants = new List<Person>();
public void RegisterParticipant(Person person)
{
_participants.Add(person);
}
public void SendGroupMessage(string senderName)
{
var participants = _participants.Where(e => e.Name != senderName);
foreach (var participant in participants)
{
participant.Notify($"{senderName} says hello to {participant.Name}");
}
}
public void SendPrivateMessage(string senderName, string listenerName)
{
var participant = _participants.First(e => e.Name == senderName);
participant.Notify($"{senderName} says hello {participant.Name}");
}
}
public static void Main()
{
// ChatRoom is our mediator instance
var chatRoom = new ChatRoom();
// Register chat participants
chatRoom.RegisterParticipant(new Person("John"));
chatRoom.RegisterParticipant(new Person("Sajid"));
chatRoom.RegisterParticipant(new Person("Rebecca"));
chatRoom.RegisterParticipant(new Person("Mo"));
// The mediator decouples communication between the chat participants
chatRoom.SendGroupMessage("John");
chatRoom.SendGroupMessage("Mo");
chatRoom.SendPrivateMessage("John", "Mo");
chatRoom.SendPrivateMessage("Rebecca", "Sajid");
// Console output:
// John says hello Sajid
// John says hello Rebecca
// John says hello Mo
// Mo says hello John
// Mo says hello Sajid
// Mo says hello Rebecca
// John says hello Mo
// Rebecca says hello Sajid
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment