Definition: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.
participants
The classes and/or objects participating in this pattern are:
Mediator(IChatroom)
defines an interface for communicating with Colleague objects
ConcreteMediator(Chatroom)
implements cooperative behavior by coordinating Colleague objects
knows and maintains its colleagues
Colleague classes(Participant)
each Colleague class knows its Mediator object
each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague
This structural code demonstrates the Mediator pattern facilitating loosely coupled communication between different objects and object types. The mediator is a central hub through which all interaction must take place.
This real-world code demonstrates the Mediator pattern facilitating loosely coupled communication between different Participants registering with a Chatroom. The Chatroom is the central hub through which all communication takes place. At this point only one-to-one communication is implemented in the Chatroom, but would be trivial to change to one-to-many.
class MainApp { staticvoid Main() { // Create chatroom Chatroom chatroom = new Chatroom();
// Create participants and register them Participant George = new Beatle("George"); Participant Paul = new Beatle("Paul"); Participant Ringo = new Beatle("Ringo"); Participant John = new Beatle("John") ; Participant Yoko = new NonBeatle("Yoko");
// Chatting participants Yoko.Send ("John", "Hi John!"); Paul.Send ("Ringo", "All you need is love"); Ringo.Send("George", "My sweet Lord"); Paul.Send ("John", "Can't buy me love"); John.Send ("Yoko", "My sweet love") ;