BehavioralC++verifiedVerified

Mediator Pattern in C++

Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.

How to Implement the Mediator Pattern in C++

1Step 1: Define the Mediator interface

class Mediator {
public:
    virtual ~Mediator() = default;
    virtual void notify(const Colleague* sender, const std::string& event) = 0;
};

2Step 2: Base colleague

class Colleague {
protected:
    Mediator* mediator_;
    std::string name_;
public:
    Colleague(Mediator* m, std::string name) : mediator_(m), name_(std::move(name)) {}
    virtual ~Colleague() = default;
    const std::string& name() const { return name_; }
};

3Step 3: Concrete colleagues

class Button : public Colleague {
public:
    using Colleague::Colleague;
    void click() {
        std::cout << name_ << " clicked\n";
        mediator_->notify(this, "click");
    }
};

class TextBox : public Colleague {
    std::string text_;
public:
    using Colleague::Colleague;
    void setText(const std::string& t) {
        text_ = t;
        mediator_->notify(this, "textChanged");
    }
    const std::string& getText() const { return text_; }
    void clear() { text_.clear(); }
};

4Step 4: Concrete mediator coordinates colleagues

class FormMediator : public Mediator {
    Button* submitBtn_;
    TextBox* inputBox_;
public:
    void setComponents(Button* btn, TextBox* box) {
        submitBtn_ = btn;
        inputBox_ = box;
    }

    void notify(const Colleague* sender, const std::string& event) override {
        if (event == "click" && sender == submitBtn_) {
            std::cout << "Form submitted: " << inputBox_->getText() << "\n";
            inputBox_->clear();
        } else if (event == "textChanged") {
            std::cout << "Input changed\n";
        }
    }
};

int main() {
    FormMediator mediator;
    Button submitBtn(&mediator, "Submit");
    TextBox inputBox(&mediator, "Input");
    mediator.setComponents(&submitBtn, &inputBox);

    inputBox.setText("Hello");
    submitBtn.click();
}

Mediator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mediator Pattern in the Real World

An air traffic control tower is the classic example. Instead of every plane communicating directly with every other plane—a chaotic and dangerous mess—all aircraft talk only to the control tower. The tower mediates all interactions, directing each plane based on the overall picture it maintains. Planes are decoupled from each other entirely.