Design patterns are used to solve common design problems and reduce the complexities in our code. The mediator pattern is a behavioral design pattern that promotes loose coupling between objects and helps to organize the code for inter-object communications.

This article presents a discussion of the mediator design pattern and how it can be implemented using C#.

What is the mediator design pattern? 

Imagine an application in which there are many objects that are communicating with each other. The mediator design pattern is useful when the number of objects grows so large that it becomes difficult to maintain the references to the objects. The mediator is essentially an object that encapsulates how one or more objects interact with each other. The mediator design pattern controls how these objects communicate, and helps to reduce the number of dependencies among them that you have to manage.

In the mediator design pattern, the objects don’t communicate with one another directly but through the mediator. When an object needs to communicate with another object or a set of objects, it transmits the message to the mediator. The mediator then transmits the message to each receiver object in a form that is understandable to it.

:

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.

Note that the mediator design pattern differs from the facade design pattern. The mediator pattern facilitates how a set of objects interact, while the facade pattern simply provides a unified interface to a set of interfaces in the application. Thus the mediator pattern is a behavior pattern that deals with object behavior, the facade pattern is a structural pattern that deals with object composition.

Implementing the mediator design pattern in C#

But enough of the concepts—let’s get into some code. The participants in this design are the mediator, the concrete mediator, and one or more participant types. While the mediator is responsible for defining the interface for communicating with the participants, the concrete mediator, as the name suggests, implements the mediator interface and has knowledge of the participants. Note that the participant type is sometimes called a colleague. So in some implementations, you have colleague and concrete colleague types.

Now, refer to the following interface. This is the interface for the mediator we will be using in this example.