> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/design-pattern/behavioural-design-pattern/mediator.md). Agents can also search and read this documentation through its [MCP server](https://javascript-1.gitbook.io/design-pattern/~gitbook/mcp).

# Mediator

Defines simplified communication between classes.

* Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
* The Mediator pattern provides central authority over a group of objects by encapsulating how these objects interact.
* The Mediator patterns are useful in the development of complex forms.

![Mediator Working Flow](https://1698315463-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LiuzoHqHr4MUK1nJBO8%2F-LqAejCHgPzLo5noM4OR%2F-LqAn_Win0uiSnf6kPcU%2Fimage.png?alt=media\&token=1799835b-dbb7-4d29-9f39-dc9c30558ddd)

```javascript
EX:
var Participant = function(name) {
    this.name = name;
    this.chatroom = null;
};
 
Participant.prototype = {
    send: function(message, to) {
        this.chatroom.send(message, this, to);
    },
    receive: function(message, from) {
        console.log(from.name + " to " + this.name + ": " + message);
    }
};
 
var Chatroom = function() {
    var participants = {};
 
    return {
 
        register: function(participant) {
            participants[participant.name] = participant;
            participant.chatroom = this;
        },
 
        send: function(message, from, to) {
            if (to) {                      // single message
                to.receive(message, from);    
            } else {                       // broadcast message
                for (key in participants) {   
                    if (participants[key] !== from) {
                        participants[key].receive(message, from);
                    }
                }
            }
        }
    };
};

function run() {
    var yoko = new Participant("Yoko");
    var john = new Participant("John");
    var paul = new Participant("Paul");
    var ringo = new Participant("Ringo");
 
    var chatroom = new Chatroom();
    chatroom.register(yoko);
    chatroom.register(john);
    chatroom.register(paul);
    chatroom.register(ringo);
 
    yoko.send("All you need is love.");
    yoko.send("I love you John.");
    john.send("Hey, no need to broadcast", yoko);
    paul.send("Ha, I heard that!");
    ringo.send("Paul, what do you think?", paul);
}

run();
```
