Mediator Pattern - Question about Colleague

Viewed 55

This is my first post, and describing this question is difficult for me.

I believe I fully understand the Mediator Pattern. My question is more on a technicality.

I have a Mediator and 3 Colleagues (C1-3).

The Mediator sends and gets back messages to/from C1. It sends and gets back messages to/from C2 as well. But with C3, it only sends one message, and does not receive any messages.

C1 and C2 are very obviously colleagues. But from a [Java] coding perspective, C3 does not have to be a Colleague. It never calls back to the mediator, so it never uses the mediator field. That's the only thing that inheritance would give it, so giving it is in a way pointless.

But on the other hand, the Mediator does use C3, so do we make it a Colleague to make that clear?

I wonder if there is a technical answer to this question or if this is just a matter of opinion.

2 Answers

The GoF book says, (page 277)

each Colleague class knows its Mediator object.

This relationship is shown clearly in several diagrams.

Mediator Structure

Now there is certainly no problem with having the Mediator make a one-way call out to another object. This would presumably be a sort of side-effect to a call initiated by a Colleague. But the object receiving that side-effect call would not itself be considered a Colleague. It would be just another object in your application, not a part of the Mediator design pattern.

Consider that unless every object in your application is a Colleague, there must be some way for information to pass in and out of the pattern, so it makes sense for a message to be sent to a non-Colleague at some point.

I guess you are referring to the Mediator example from Wikipedia, which uses Colleague classes and subclasses for demonstration purposes.

Actually, I think this example is pretty confusing, since it is overengineered. The Mediator pattern has actually nothing to do with inheritance. The gist of the mediator is that there are some objects which need to communicate with each other, but only indirectly through the mediator object. And if in your case the required communication with C3 is only unidirectional, that's fine, no need for holding a reference back to the mediator object if that's not required.

Note also that there is no "rule" or "law" in software design which says you need to implement design patterns exactly as they were introduced in the GoF book - if a simpler or partial solution is sufficient, go ahead - the GoF design patterns are suggestions how things can be implemented, no more, no less.

Related