The mediator behavioral pattern allows you to define complex object interactions while still keeping each object simple and unaware of the other objects.
Just open any user interface dialog box and notice how some controls become disabled when the state of other controls changes. Maybe there’s some text you need to enter before you can proceed. A well designed user interface will make this clear by disabling the Ok or Next button whenever the text field is empty.
The solution that this pattern describes involves a new class called the mediator which knows about all the other classes that need help with their relationships such as this text field and button. Each class just needs to refer to the mediator instead of trying to coordinate with the other classes directly.
You’ll want each of your classes to have a base class or interface with a method called notifyMediator. Whenever a class changes such as when the user types some text into a text field or deletes some text from the text field, it can call its notifyMediator method. As far as the text field is concerned, it’s done. This is simple code that can be used anywhere.
How did the text field know about the mediator? That’s the job of the mediator. The mediator will either create each control itself and then as part of the creation process, let each class know about the mediator, or it will let some other class perform the creation and then visit each class and call some method common to them all that lets the class know about the mediator. Because each class has a common interface, the mediator will be able to use this interface to inform the classes about the mediator.
Let’s look at what happens in the specific case where the user types something into the text field.
- Each key press that results in the text changing will cause the notifyMediator method to be called.
- This method then calls a changed method in the mediator and sends a pointer or reference to itself to the mediator.
- At this point, the text field has informed the mediator that something has changed and let the mediator know that it was the source of the change.
- The mediator is notified that a change has taken place and looks at the source of the change and sees that it came from the text field.
- The mediator makes a request back to the text field to get whatever text it currently contains.
- The text field responds to the method call by providing its text.
- Now that the mediator has the contents of the text field, it puts its special knowledge to work and checks the length of the string. If the string is empty, then the mediator disables the Ok button. And if the string has text in it, then the mediator enables the Ok button.