美文网首页
设计模式-发布订阅

设计模式-发布订阅

作者: Vincent_cy | 来源:发表于2020-12-11 22:44 被阅读0次

    前言

    发布订阅又叫观察者模式,它记录的是一种一对多的依赖关系,当订阅的数据状态发生改变时,所对应的依赖的对象会得到消息(通知)。

    优点

    发布订阅在异步编程中,可以替代回调,从而无需关注对象在异步运行中的内部状态,只需要关注有用的事件发生点。对象之间的解耦。

    发布-订阅的组成要素

    一个发布订阅包包含了三要素,发布者(Publisher),订阅者(Subscriber),调度处理中心(Event channel)。
    当Publisher发布一个事件到Event channel,Subscriber就会收到由Event Bus触发的事件的通知。

    发布订阅的简单实现

    class EventEmeitter {
        constructor(){
            this.events = new Map();
            this._maxListeners = this._maxListenners || 10;
        }
        // 发布
        emit(type,...args){
           let handler;
               handler = this.events.get(type);
               if(Array.isArray(handler)){
                   for(let i = 0; i < handler.length; i++){
                       if(args.length>0){
                           handler[i].apply(this,args);
                       }else{
                           handler[i].apply(this);
                       }
                   }
               }else{
                   if(args.length>0){
                       handler.apply(this,args);
                   }else{
                       handler.apply(this);
                   }
               }
               return true;
        }
        //  添加监听事件
        addEventListener(type,fn){
            const handler = this.events.get(type); // 获取对应事件名称的函数
                if(!handler){
                    this.events.set(type,fn);
                }else if(handler && typeof handler === 'function'){
                    // 如果handler是函数说明当前只有一个监听函数
                    this.events.set(type,[handler,fn]);
                }else{
                    if(handler.length <= this._maxListenners) return handler.push(fn); // 添加多个监听有上限
            }
        }
        // 移除监听事件
        removeListener(type, fn){
            const handler = this.events.get(type); // 获取对应事件名称的函数
                // 如果是函数,说明只被监听了一次
                if(handler && typeof handler === 'function'){
                    this.events.delete(type,fn);
                }else{
                    // 如果handler是数组,说明被多次监听,需要找到对应的函数的位置
                    let position;
                    for(let i = 0 ; i< handler.length; i++){
                        if(handler[i] === fn){
                            position = i
                        }else{
                            position = -1;
                        }
                    }
                    // 如果找到匹配的函数
                    if(position !== -1){
                        // 直接删除
                        handler.splice(position,1);
                        // 如果清除后只有一个函数,那么取消数组,以函数形式保存
                        if(handler.length ===1){
                            this.events.set(type,handler[0]);
                        }
                    } else {
                        return this;
                    }
                }
        }
    }
    

    例子

    发布订阅的应用场景

    比如我们很喜欢看某个公众号号的文章,但是我们不知道什么时候发布新文章,要不定时的去翻阅;这时候,我们可以关注该公众号,当有文章推送时,会有消息及时通知我们文章更新了。
    看似简单的操作,其实是一个典型的发布订阅模式,公众号属于发布者,用户属于订阅者;用户将订阅公众号的事件注册到调度中心,公众号作为发布者,当有新文章发布时,公众号发布该事件到调度中心,调度中心会及时发消息告知用户。

    基于公众号的发布订阅

    // 实例化event bus
    const eventBus = new EventEmeitter() 
    //订阅方法
    function user1(data){
        console.log(`订阅用户1`, data)
    }
    function user2(data){
        console.log(`订阅用户2`, data)
    }
    // 添加订阅
    eventBus.addEventListener('article', user1)
    eventBus.addEventListener('article', user2)
    // 发布
    eventBus.emit('article', '有新的文章发布了')
    

    欢迎访问主页,有更多文章内容
    转载请注明原出处
    原文链接地址:设计模式-发布订阅

    相关文章

      网友评论

          本文标题:设计模式-发布订阅

          本文链接:https://www.haomeiwen.com/subject/mcwsgktx.html