js 设计模式学习--观察者模式

<script>
/*---------------------------
    defined observer 
----------------------------*/
function Observer(){}//观察者
Observer.prototype.update = function(context){//观察者方法
console.log("观察者被触发1 " + context);
}
function ConcreteObserver(){}//具体观察者
ConcreteObserver.prototype.update = function(context){//具体观察者方法
    console.log("观察者被触发2 " + context);
}
/*---------------------------
    defined ObserverCollection // 观察者集合
----------------------------*/
function ObserverCollection(){// 观察者集合
    this._observers_ = new Array();  //定义数组
}
ObserverCollection.prototype.add = function(observer){//定义数组添加方法
    this._observers_.push(observer);
}
ObserverCollection.prototype.remove = function(observer){//定义数组删除方法
    if(_observers_ == null || _observers_=="undefined"){
        return null;
    }
    for(var dx=0; dx < this._observers_.length; dx++){
        if(this._observers_[dx] == observer){
            this.splice(this._observers_[dx],1);
        }
    }      
}
ObserverCollection.prototype.count = function(){//定义观察者集合个数
    return this._observers_.length;
}
ObserverCollection.prototype.getAt = function(index){//根据索引得到具体的莫个观察者
    if (index > -1 && index < this._observers_.length){
        return this._observers_[index];
    }
    return undefined;
}
/*---------------------------
    defined Subject 
----------------------------*/
function EmergencyCase(obj){
    this.name = name;
    this._obs_ = new ObserverCollection();
}
//新案件
EmergencyCase.prototype.add = function(ob){//添加观察者对象
    if (ob.update){
        this._obs_.add(ob);
    }
}
//案件状态改变
EmergencyCase.prototype.stateChanged = function(newStatus,caseNo){
    var ob;
    for(var i=0; i < this._obs_.count(); i++)
    {
        ob = this._obs_.getAt(i);
        ob.update(newStatus,caseNo);    
    }
}
//分局下发案件
EmergencyCase.prototype.deliverCase = function(caseNo,acceptDepartment, deliverComment){
    if (this.name != newName){
        this.name = newName;
        this.nameChanged();
    }
}
function test(){
    var sub = new EmergencyCase("jjy");
console.log('创建被观察者');
    sub.add(new Observer());
console.log('增加观察者');
    sub.add(new ConcreteObserver());
console.log('增加另一个观察者');
console.log('改变状态');
    sub.stateChanged("Send","01102331234567");
   // sub.stateChanged("Quit","01102331234567");
}
test();
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值