class Mediator;class Button{public: Button(Mediator *mediator) {_mediator = mediator;} void click() {_mediator->buttonClicked(this);} void autoClick() {}private: Mediator _mediator;};class Mediator{public: Mediator() {} void addButton(Button *button) {_buttons.append(button);} void buttonClicked(Button *button) { for(int i = 0, n = buttons.size(); i < n; ++i) { if(button == buttons.at(i)) continue; buttons.at(i)->autoClick(); } }private: List<Button*> _buttons;};
class Mediator;class Widget{public: Widget(Mediator *mediator, const String &caption) {_mediator = mediator; _caption = caption;} virtual Mediator::WidgetType type() const = 0; void click() {_mediator->widgetClicked(this);} void setCaption(const String &new_caption) {_caption = new_caption;}private: Mediator *_mediator; String _caption;};class Button : public Widget{public: Button(const String &caption, Mediator *mediator) : Widget(mediator, caption) {} Mediator::WidgetType type() const {return Mediator::WT_BUTTON;}};class Label : public Widget{public: Label(const String &caption, Mediator *mediator) : Widget(mediator, caption) {} Mediator::WidgetType type() const {return Mediator::WT_LABEL;}};class Mediator{public: enum WidgetType {WT_BUTTON, WT_LABEL}; Mediator() {} void addWidget(Widget *widget) {_widgets.insertMulti(widget->type(), widget);} void widgetClicked(Widget *widget) { QList<Widget*> widgets; String new_caption; switch(widget->type()) { case Mediator::WT_BUTTON: { widgets = _widgets.values(Mediator::WT_LABEL); new_caption = "button clicked"; } break; case Mediator::WT_LABEL: { widgets = _widgets.values(Mediator::WT_BUTTON); new_caption = "label clicked"; } break; } for(int i = 0, n = widgets.size(); i < n; ++i) { widgets.at(i)->setCaption(new_caption); } }private: Hash<WidgetType, Widget*> _widgets;};