Delegate Example Explained With Mediator Pattern

There are many articles published about delegates and events but few about their practical usage in the real world. This is one among them. It has less (or nothing) of an explanation of what delegates and events are. Instead I have tried to fit delegates into a mediator pattern and shown theirpractical usage. So you get the bonus of knowing about the mediator pattern as well as understanding delegates.

Delegates can be used for communication between two layers. One layer can subscribe to the event and the other can continue notifying. Let's see this with an example.

We will have a main form with a text box in it. We will also add 2 user controls that contain a TextBox in each. When text is entered into the main form's TextBox it needs to notify the UesrControl's TextBox.

Create two UesrControls, each with a TextBox as shown in the following screenshot:

                     squre

UesrControls

Add these two user controls to the main form.

user controls in the main form

Now create a Mediator class as a singleton so that only a single instance of it can be created. Also create a delegate and event.

delegate and event

In usercontrol1 and usercontrol2 initialize this delegate. Since the delegate is essentially a pointer to a method that has a string as parameter, set the text value of the TextBox to a string.

cs code

textbox

The role of the delegate is to pass the text entered into the MainForm to both of the user controls. We will add a text changed event to the main form and publish the event whenever there is a change in the text.

change in the text
That's the end of whenever the text changes in the main form, it keeps sending a notification without knowing to whom it is sending. The other way, all the notification receivers will not be aware of who is sending the notifications. Hence the delegate helps us in creating a publisher subscriber model in a loosely coupled manner.


Similar Articles