Skip to content

Instantly share code, notes, and snippets.

@sag1v
Last active April 3, 2019 10:59
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 sag1v/c25a249efcad611ce73eac8ec145429e to your computer and use it in GitHub Desktop.
Save sag1v/c25a249efcad611ce73eac8ec145429e to your computer and use it in GitHub Desktop.
Just a poc of the mediator pattern
// with class pattern
class Client {
constructor(name) {
this.name = name;
this.mediator = null;
}
send(message, to) {
if (!this.mediator) {
throw ('you need to register to a mediator first')
}
this.mediator.send(message, this, to);
}
receive(message, from) {
console.log(from.name + " to " + this.name + ": " + message);
}
}
class Mediator {
constructor() {
this.clients = {};
}
register(client) {
this.clients[client.name] = client;
client.mediator = this;
}
send(message, from, to) {
if (to) {
to.receive(message, from);
} else {
for (const key in this.clients) {
if (this.clients[key] !== from) {
this.clients[key].receive(message, from);
}
}
}
}
}
var user1 = new Client("user1");
var user2 = new Client("user2");
var user3 = new Client("user3");
var user4 = new Client("user4");
var mediator = new Mediator();
mediator.register(user1);
mediator.register(user2);
mediator.register(user3);
mediator.register(user4);
user1.send("Hi all i'm user1");
user1.send("Hi user3");
user2.send("talk in private", user1);
user4.send("get a room!", user1);
user3.send("Hi, i'm here", user1);
// with constructor functions pattern
function Client(name) {
this.name = name;
this.mediator = null;
}
Client.prototype.send = function(message, to) {
if (!this.mediator) {
throw ('you need to register to a mediator first')
}
this.mediator.send(message, this, to);
}
Client.prototype.receive = function(message, from) {
console.log(from.name + " to " + this.name + ": " + message);
}
function Mediator() {
this.clients = {};
}
Mediator.prototype.register = function(client) {
this.clients[client.name] = client;
client.mediator = this;
}
Mediator.prototype.send = function(message, from, to) {
if (to) {
to.receive(message, from);
} else {
for (const key in this.clients) {
if (this.clients[key] !== from) {
this.clients[key].receive(message, from);
}
}
}
}
var user1 = new Client("user1");
var user2 = new Client("user2");
var user3 = new Client("user3");
var user4 = new Client("user4");
var mediator = new Mediator();
mediator.register(user1);
mediator.register(user2);
mediator.register(user3);
mediator.register(user4);
user1.send("Hi all i'm user1");
user1.send("Hi user3");
user2.send("talk in private", user1);
user4.send("get a room!", user1);
user3.send("Hi, i'm here", user1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment