Mediator Pattern

This pattern is best illustrated in code as the source describes it a lot more concisely than in prose. One central class (the mediator) is used by many ‘client’ classes to send messages with (n.b. ‘client’ is my own term not one from the original pattern description). A ‘client’ or several ‘client’ classes then have a reference to this mediator instance as a private field, and use it to send messages. The mediator has an event which each ‘client’ subscribes to. This event is fired each time the mediator sends a message.


Example
A chat room could use the Mediator pattern, or a system where many ‘clients’ each receive a message each time one of the other clients performs an action (for chat rooms, this would be when each person sends a message). In reality using the Mediator pattern for a chat room would only be practical when used with remoting. Using raw sockets wouldn’t allow for the delegate callbacks (people subscribed to the Mediator class’ MessageReceived event).  

Implementation
namespace DesignPatterns
{
    public delegate void MessageReceivedEventHandler(string message, string from);
 
 public class Mediator
 {
  public event MessageReceivedEventHandler MessageReceived;
  public void Send(string message, string from)
  {
   if (MessageReceived != null)
   {
    Console.WriteLine("Sending '{0}' from {1}", message, from);
    MessageReceived(message, from);
   }
  }
 }
 
 public class Person
 {
  private Mediator _mediator;
  public string Name { get; set; }
  public Person(Mediator mediator, string name)
  {
   Name = name;
   _mediator = mediator;
   _mediator.MessageReceived += new MessageReceivedEventHandler(Receive);
  }
  private void Receive(string message, string from)
  {
   if (from != Name)
    Console.WriteLine("{0} received '{1}' from {2}", Name, message, from);
  }
  public void Send(string message)
  {
   _mediator.Send(message, Name);
  }
 }
}

Comments

Popular posts from this blog

Facade Design Pattern

Auto Scroll in Common Controls

Convert typed library (.tlb) to .net assembly?