Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created August 19, 2020 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velotiotech/43dbe01ca3df17d32bfff73d4b167f13 to your computer and use it in GitHub Desktop.
Save velotiotech/43dbe01ca3df17d32bfff73d4b167f13 to your computer and use it in GitHub Desktop.
// each participant represented by Participant object
class Participant {
constructor(name) {
this.name = name;
}
getParticiantDetails() {
return this.name;
}
}
// Mediator
class Chatroom {
constructor() {
this.participants = {};
}
register(participant) {
this.participants[participant.name] = participant;
participant.chatroom = this;
}
send(message, from, to) {
if (to) {
// single message
to.receive(message, from);
} else {
// broadcast message to everyone
for (key in this.participants) {
if (this.participants[key] !== from) {
this.participants[key].receive(message, from);
}
}
}
}
}
// usage
// Create two participants
const john = new Participant('John');
const snow = new Participant('Snow');
// Register the participants to Chatroom
var chatroom = new Chatroom();
chatroom.register(john);
chatroom.register(snow);
// Participants now chat with each other
john.send('Hey, Snow!');
john.send('Are you there?');
snow.send('Hey man', yoko);
snow.send('Yes, I heard that!');
@james0r
Copy link

james0r commented Apr 4, 2021

Looks like this was adapted from this -> dofactory design patterns - mediator

I fixed the errors if anywhere cares to check it out -> https://glitch.com/edit/#!/javascript-mediator-pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment