Printed from www.rmfusion.com A Developer website designed for Developers

Mediator Pattern Code Review

Code Download

Define the Mediator Object

Define the Mediator class (object) which is responsible for managing messages that are exchanged between colleagues.

class Mediator { public delegate void Callback (String message, String from); Callback respond;
public void SignOn(Callback method) { respond += method; } public void Block(Callback method) { respond -= method; } public void Unblock(Callback method) { respond += method; } public void Send(String message, String from) { respond(message, from); Console.WriteLine(); } }

Callback methods are used to invoke the Receive() method on the relevant Colleagues classes (objects).

Define the Colleague Objects

The Colleague class (object) represents the person who either sends or receives messages through the mediator.

class Colleague { Mediator m_mediator; protected String m_name;
public Colleague(Mediator mediator, String name) { this.m_mediator = mediator; mediator.SignOn(this.Receive); this.m_name = name; }
public virtual void Receive(String message, String from) { if (!String.Equals(from, this.m_name)) { Console.WriteLine("Colleague {0} received from {1}: {2}", this.m_name, from, message); } } public void Send(String message) { Console.WriteLine("Colleague Send (From {0}): {1}", this.m_name, message); this.m_mediator.Send(message, this.m_name); } }

Each instance of the Colleague class (object) will register itself with the Mediator class (object) using the SignOn() method. Messages will be send by invoking the Send() method on the Mediator class (object).

The ColleagueB class (object) is essentially another version of the Colleague class (object) and represents the person who either sends or receives messages through the mediator.

class ColleagueB : Colleague { public ColleagueB(Mediator mediator, String name) : base(mediator, name) { }
public override void Receive(string message, string from) { if (!String.Equals(from, this.m_name)) { Console.WriteLine("ColleagueB {0} received from {1}: {2}", this.m_name, from, message); } } }

Use the Mediator Pattern

The Program class creates the Mediator object and various Colleague objects.

class Program { static void Main(string[] args) { Mediator m = new Mediator();
Colleague head1 = new Colleague(m, "John"); ColleagueB branch1 = new ColleagueB(m, "David"); Colleague head2 = new Colleague(m, "Lucy");
head1.Send("Meeting on Tuesday, please all ack"); branch1.Send("Ack"); m.Block(branch1.Receive); head1.Send("Still awaiting some Acks"); head2.Send("Ack"); m.Unblock(branch1.Receive); head1.Send("Thanks all");
Console.Read(); } }

Messages are then exchanged between the Colleague objects, through the Mediator object.