《论 · 前端设计模式之一:发布订阅者模式》

144 阅读1分钟

有的人觉得观察者模式和发布订阅模式是一样的,但同样的也有人觉得不是一样的,那么,让我来举个栗子,你就明白了,两个有什么区别,观察者模式可以康康我的上一篇文章哈!!!!

```//发布订阅者模式
        class Observer{
            constructor(){
                this.message = {}
            }
            subscribe(type,fn = () => {}){ //需要订阅的书和需要处理的方式
                if(!this.message[type]){
                    this.message[type] = []
                }
                this.message[type].push(fn)
                // console.log(this.message[type]);
            }
            cancelSubscribe(type,fn){ //用户可以取消订阅
                if(!fn){ 
                    delete this.message[type];
                    return
                }
                if(!type) return ;
                this.message[type] = this.message[type].filter((item)=>{
                    item == fn
                })

            }
            trigger(type){ //开始进货,通知用户过来拿书
                if(!type) return ; 
                this.message[type].forEach((item)=>{
                    item()
                })
            }
        }

    let PDX = new Observer(); //派大星(实例对象)
    let HMBB = new Observer(); //海绵宝宝(实例对象)
    let ZYG = new Observer(); //章鱼哥(实例对象)

    //这是我们一会书到了要通知每个订阅者需要做的事
    function funPDX(){ console.log('你的书到了派大星') };
    function funHMBB(){ console.log('海绵宝宝这是你订阅的书') };
    function funZYG(){ console.log('章鱼哥你的书到了,来拿一下') };

    //现在我们开始采购每个客户要的书
    PDX.subscribe('《Javascript百炼成仙》',funPDX)
    HMBB.subscribe('《凡人修Vue传》',funHMBB)
    ZYG.subscribe('《隔壁的React》',funZYG)

    // console.log(PDX);
    PDX.trigger('《Javascript百炼成仙》') // 开始采购
    
    控制台会打印出 你的书到了派大星