Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

Structure of design pattern

Mediator pattern structure


// Common mediator interface.
interface Mediator is
    method notify(type: string, sender: Component)

// Concrete mediator. All chaotic communications between concrete components
// have been extracted to the mediator. Now components only talk with the
// mediator, which knows who has to handle a request.
class AuthenticationDialog implements Mediator is
    field title: string
    field loginOrRegister: Checkbox
    field loginUsername, loginPassword: Textbox
    field registrationUsername, registrationPassword, registrationEmail: Textbox
    field ok, cancel: Button

    constructor AuthenticationDialog() is
        Create all component objects.
        Pass "this" to their constructor to register itself as a mediator.

    method notify(type, sender) is
        if (type == "check" and sender == loginOrRegister)
            Show login fields, hide registration fields or vise versa.
            if (loginOrRegister.checked)
                title = "Log in"
                title = "Register"
        if (type == "click" and sender == ok)
            if (loginOrRegister.checked)
                Try to find user using login credentials.
                if (!found)
                    Show errors over login fields.
                Create account using registration fields.
                Log user in.
        // ...

// Component classes communicate with mediator using common mediator interface.
// Thanks to that, you can use the same components with different mediators.
class Component is
    field parent: Mediator

    constructor Component(parent) is
        this.parent = parent

    method click() is
        parent.notify("click", this)

    method keypress() is
        parent.notify("keypress", this)

// Concrete components don't talk with each other. They have only one
// communication channel–sending requests to the mediator.
class Button extends Component is
    // ...

class Textbox extends Component is
    // ...

class Checkbox extends Component is
    method check() is
        parent.notify("check", this)
    // ...

Implementations in Different Programming Languages