Created
August 19, 2020 05:20
-
-
Save velotiotech/43dbe01ca3df17d32bfff73d4b167f13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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