Mediator Pattern
Summary: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Sample Code
Code
public class Person
{
public string Name;
public ChatRoom Room;
private List<string> chatLog = new List<string>();
public Person(string name)
{
Name = name;
}
public void Receive(string sender, string message)
{
string s = $"{sender}: '{message}'";
System.Console.WriteLine($"[{Name}'s chat session] {s}");
chatLog.Add(s);
}
public void Say(string message)
{
Room.Broadcast(Name, message);
}
public void PrivateMessage(string who, string message)
{
Room.Message(Name, who, message);
}
}
public class ChatRoom
{
private List<Person> people = new List<Person>();
public void Broadcast(string source, string message)
{
foreach (var p in people)
if (p.Name != source)
p.Receive(source, message);
}
public void Join(Person p)
{
string joinMsg = $"{p.Name} joins the chat";
Broadcast("room", joinMsg);
p.Room = this;
people.Add(p);
}
public void Message(string source, string destination, string message)
{
people.FirstOrDefault(p => p.Name == destination)?.Receive(source, message);
}
}
Usage
var room = new ChatRoom();
var admin = new Person("Admin");
var user1 = new Person("User1");
var user2 = new Person("User2");
room.Join(admin);
room.Join(user1);
room.Join(user2);
user1.Say("hi room");
user2.Say("oh, hey user1");
var guru = new Person("guru");
room.Join(guru);
guru.Say("hi everyone!");
user1.PrivateMessage("guru", "I need some info...");
Output
[Admin's chat session] room: 'User1 joins the chat'[Admin's chat session] room: 'User2 joins the chat'
[User1's chat session] room: 'User2 joins the chat'
[Admin's chat session] User1: 'hi room'
[User2's chat session] User1: 'hi room'
[Admin's chat session] User2: 'oh, hey user1'
[User1's chat session] User2: 'oh, hey user1'
[Admin's chat session] room: 'guru joins the chat'
[User1's chat session] room: 'guru joins the chat'
[User2's chat session] room: 'guru joins the chat'
[Admin's chat session] guru: 'hi everyone!'
[User1's chat session] guru: 'hi everyone!'
[User2's chat session] guru: 'hi everyone!'
[guru's chat session] User1: 'I need some info...'
Comments
Post a Comment