Posted on Tuesday February 10, 2009

C# Design Patterns: the Mediator pattern

Summary

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).