Define an object that encapsulates how a set of objects interact; the mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently. Use when a set of objects communicate in complex ways and reusing individual objects is difficult because they reference many peers.
Examples:
- A profile-editing dialog has checkboxes, text fields, and a submit button that all affect each other (e.g., checking 'I have a dog' reveals a name field; submit validates all fields). Making each control aware of the others creates a tangled web. With Mediator, the dialog class itself mediates — controls notify the mediator of changes and the mediator decides what to update, keeping each control reusable in isolation.
class Mediator {
public:
virtual void ColleagueChanged(Colleague*) = 0;
};
class Colleague {
protected:
Mediator* mediator;
public:
void Changed() { mediator->ColleagueChanged(this); }
};
class ConcreteMediator : public Mediator {
void ColleagueChanged(Colleague* c) override { /* coordinate peers */ }
};
Synonyms: intermediary, controller