Design pattern - Observer pattern (publish and subscribe pattern).

Observer pattern

In layman's terms, the observer mode is God's perspective, and its core idea is one-to-many .

For example, in a game guild, some collective events in the guild need to be distributed to each member's mailbox. Since the same message is distributed to different hands, this can be called the observer mode.

When each object changes, related dependent objects are notified and updated automatically.

var pubsub = {
    
    
        list: {
    
    },//存储订阅事件
        subscribe: function (key, fn) {
    
    
            //添加订阅方法
            if (!this.list[key]) {
    
    
                this.list[key] = [];
            }
            this.list[key].push(fn);
        },
        publish: function (key,time) {
    
    
            //发布订阅
            for (var index in this.list[key]) {
    
    
                this.list[key][index].call(this,time);
            }
        },
        unpublish: function (key, fn) {
    
    
            var that=this;
            //取消订阅
            if (!that.list[key])
                return;
            if(!fn)
            {
    
    
                console.log('fn参数不存在!');
            }
            else{
    
    
                if(typeof fn=='function')
                {
    
    
                    that.list[key].map(function (f,index){
    
    
                        if(f===fn)
                        {
    
    
                            that.list[key].splice(index,1);
                        }
                    });
                }
                else{
    
    
                    console.log('fn参数不是函数!');
                }
            }

        }
    }

    //订阅
    pubsub.subscribe('gowork',function (time){
    
    
        console.log("上班了~打卡时间为:"+time);
    });
    pubsub.subscribe('backwork',work);
    function work(time){
    
    
        console.log("下班了~打卡时间为:"+time);
    }

    console.log(pubsub.list);

    //发布订阅
    pubsub.publish('gowork','08:50:00');
    pubsub.publish('backwork','17:30:00');

    //取消订阅
    pubsub.unpublish('backwork',work);

    console.log(pubsub.list);


Guess you like

Origin blog.csdn.net/weixin_46953330/article/details/118959891