» The Mediator pattern enables objects to communicate without knowing each other's identities; » The Mediator pattern is used in many modern systems that reflect a send/receive protocol; » The Mediator pattern can have a performance impact on a system because all communication must go through the mediator and it can become a bottleneck.
Use When:
» Objects communicate in well-structured but potentially complex ways; » The objects identities should be protected even though they communicate; » Some object behaviours can be grouped and customized.
// Define the Mediator Object.
//Define the Mediator class (object) which is responsible for managing messages that are exchanged between colleagues. //Callback methods are used to invoke the Receive() method on the relevant Colleagues classes (objects). public classMediator { public delegate voidCallback(string message, string from);
privateCallback _respond;
public void SignOn(Callback method) { _respond += method; }
public void Block(Callback method) { _respond -= method; }
public void Unblock(Callback method) { _respond += method; }
//The Colleague class (object) represents the person who either sends or receives messages through the mediator. //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). public classColleague { protectedMediator Mediator; protected string Name;
public Colleague(Mediator mediator, string name) { Mediator = mediator; mediator.SignOn(Receive); Name = name; }
public virtual void Receive(string message, string from) { if (!string.Equals(from, Name)) { Console.WriteLine("Colleague {0} received from {1}: {2}", Name, from, message); } }
//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. public classColleagueB : Colleague { public ColleagueB(Mediator mediator, string name) : base(mediator, name) { }
public override void Receive(string message, string from) { if (!string.Equals(from, Name)) { Console.WriteLine("ColleagueB {0} received from {1}: {2}", Name, from, message); } } }