JS Mediator Pattern ——用作聊天室

本文介绍了如何运用Mediator模式创建一个聊天室。通过定义User类及其prototype函数send和receive,以及chatroom类作为中介者,实现用户间消息的发送与接收。在chatroom类中,register方法用于注册用户,并为用户赋予chatroom对象;send方法根据是否有指定接收对象,调用相应用户的receive函数,实现消息传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值