javascript设计模式之Observer(观察者)模式

本文深入探讨了Observer(观察者)设计模式,解释了其基本概念,如何在JavaScript中实现Observer模式,并将其与Publish/Subscribe模式进行了比较。通过具体的代码示例,展示了如何创建Subject和Observer,以及如何在实际应用中进行测试。

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

 具体概念

Observer(观察者)是一种设计模式,一个对象(subject)维持一系列依赖于它(观察者)的对象,将任何状态的任何变更自动通知给它们。


Suject(目标)

维护一系列的观察者,方便添加或者删除观察者。

Observer(观察者)

为那些在目标状态发生改变时需获得通知的对象提供更新接口

代码实现

  所依赖的代码

function ObserverList(){
    this.observerList=[];
}
ObserverList.prototype.Add=function(obj){
    return this.observerList.push(obj);
};
ObserverList.prototype.RemoveIndexAt=function(index){
        this.observerList.splice(index,1);
};
ObserverList.prototype.Count=function(){
    return this.observerList.length;
};
ObserverList.prototype.Get=function(index){
    if(index > -1 && index < this.observerList.length){
        return this.observerList[index];
    }
};

接着,我们建立Subject(目标)

function Subject(){
    this.observers=new ObserverList();
}
Subject.prototype.AddObserver=function(observer){
    this.observers.Add(observer);
};
Subject.prototype.RemoveObserver=function(observer){
    this.observers.RemoveIndexAt(this.observers.indexOf(observer));
}
Subject.prototype.Notify=function(context){
    var observerCount=this.observers.Count();

    for(var i= 0; i < observerCount; i++){
        this.observers.Get(i).Update(context);
    }
}

建立Observer

function Observer(){
    this.Updata=function(){
           //具体的操作
   }
}


Observer模式和Publish/Subscribe模式

Observer模式一般会使用一个成为Publish/Subscribe模式的变量来实现。Publish/Subscribe模式使用的是主题/事件通道,这个通道介于希望接收到通知的对象(订阅者)和激活事件的对象(发布者)之间。该事件系统允许代码自定义应用程序的特定事件,这些事件乐意传递自定义参数,自定义参数包含订阅者所需的值,其目的是避免订阅者和发布者之间产生关系。

                             


代码实现


var pubsub={};
(function(q){
    var topics={},
        subUid=-1,
        subscribers,
        len;
    //发布广播事件,包含特定的topic名称和参数
    q.publish=function(topic, args){
        if(!topics[topic]){
            return false;
        }

        subscribers=topics[topic];
        len=subscribers ? subscribers.length : 0;

        while(len--){
            subscribers[len].func(topic, args);
        }
        return this;
    };
    q.subscribe=function(topic, func){
        if(!topics[topic]){
            topics[topic]=[];
        }

        var token=(++subUid).toString();
        topics[topic].push({
            token:token,
            func:func
        });
        return token;
    };

    q.unsubscribe=function(token){
        for(var m in topics){
            if(topics[m]){
                for(var i = 0, j=topics[m].length; i < j; i++){
                    if(topics[m][i].token === token){
                        topics[m].splice(i, 1);
                        return token;
                    }
                }
            }
        }
        return this;
    };
})(pubsub);


测试

   function log1(topic ,data){
        console.log(topic , data)
    }
    function log2(topic ,data){
        console.log("Topic is "+topic+" Data is "+data);
    }
    pubsub.subscribe("sss",log1);
    pubsub.subscribe("cccc",log2);
    pubsub.publish("sss","aaaaa1");
    pubsub.publish("sss","aaaaa2");
    pubsub.publish("cccc","ssssss");










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值