Mediator Pattern
定义User类的构造函数
const User = function(name){
this.name = name;
this.chatroom = null;
}
为User类添加prototype函数
(1)send函数中,用到chatroom类对象的send函数;
(2)revieve函数中,显示recieve的内容在console.log上;
User.prototype ={
send:function(message,to){
this.chatroom.send(message,this, to);
},
recieve:function(message,from){
console.log(`${from.name} to ${this.name}: ${message}`);
}
}
chatroom类(mediator)
定义public函数:
(1)register:保存user,且赋予user.chatroom对象;
(2)send:
若有给定对象to:调用to对象的recieve函数;
若无给定对象to:对每个user都调用recieve函数;
const Chatroom=function(){
let users={}; //list of users
return {
register: function(user){
users[user.name] = user;
user.chatroom = this;
},
send:function(message,from,to){
if(to){
//Single user message
to.recieve(message,from);
}else{
//Mass message
for(key in users){
if(users[key]!== from){
users[key].recieve(message,from);
}
}
}
}
}
}
调用类和methods
const brad = new User('Brad');
const jeff = new User('Jeff');
const sara = new User('Sara');
const chatroom = new Chatroom();
chatroom.register(brad);
chatroom.register(jeff);
chatroom.register(sara);
brad.send('nihao',jeff);
brad.send('sara',sara);
sara.send('brad',brad);
sara.send('hello');