PDA

View Full Version : Mediator Pattern



cosmicloverocks
February 24th, 2010, 11:41 PM
Can you guys explain what is the role of mediator on MVC? Perhaps provide a real work example like managing states?

ayumilove
February 25th, 2010, 07:49 AM
Can you guys explain what is the role of mediator on MVC? Perhaps provide a real work example like managing states?

mediator pattern can be found in many
design patterns such as:
- factory pattern,
- state pattern,
- etc

in my opinion, mediator should not be seen as a pattern
but more of a technique that make classes loosely coupled.

a simple analogy would be a supermarket (acting as the mediator).
the supermarket interacts with the customers (to sell crops to them)
the supermarket interacts with the farmer (to buy crops from them)

if there is no mediator, each customer have
to visit each farmer to get their goods,
which is a lot of hassle and waste of time.

/////////////////////////////////////////////////////////

ok now lets take another example :
a mediator pattern exist in other patterns such as state pattern.

if we were to take a car (with auto-gear) as our example,
each car have a few states, the common ones are:
- parking state
- neutral state
- reversing state
- driving state

usually, in state pattern would have each
state communicating with one another.

If player changes from driving-gear to parking-gear
while in driving state, the driving state communicate
directly to the parking-gear. And the parking-gear
just do its job.

As more car states begin to communicate
with one another without any middleman/mediator,
it creates a spaghetti pattern (i create this term f3),
which basically means each class is tightly coupled
with one another, by exchanging links to one another.

If you try to remove the meatball (one of the classes)
from the spaghetti, errors starts surfacing...
You would need to recode other classes for the
missing/removed class. Lots of hassle.

Now this is where mediator pattern/technique steps in.
The common thing about mediator is:
- mediator knows all the classes.
(if it does not know, then he can't link 1 class to the other class)
(just like how supermarket does it)