hytzgroup / blog

write & read & though
0 stars 0 forks source link

观察者模式 #18

Open hytzgroup opened 4 years ago

hytzgroup commented 4 years ago
/**
    One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. 
    一个或者多个观察者观察一个对象的某个状态,并且把自己加入到他们感兴趣的状态中。
    When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. 
    当观察者感兴趣的某个状态发生变化,通过调用观察者的update方法来接收消息。
    When the observer is no longer interested in the subject's state, they can simply detach themselves.
    当观察者对某个状态不在感兴趣,它可以简单的把自己移除。
 */
function ObserverList(){
    this.state = [];
}
ObserverList.prototype = {
    constructor:ObserverList,
    add:function(observer){
        this.state.push(observer);
    },
    remove:function(observer){
        var eObserver = null;
        for(var i = 0, len = this.state.length; i < len; i++){
            eObserver = this.state[i];
            if(eObserver === observer){
                this.state.splice(i,1);
                return;
            }
        }
    },
    notify:function(msg){
        var eObserver = null;
        for(var i = 0, len = this.state.length; i < len; i++){
            eObserver = this.state[i];
            eObserver.update(msg);
        }
    }
};

function Observer(){
    this.update = function(mgs){
        console.log('update--->>>',mgs);
    }
}

function Subject(){
    this.xxxState = new ObserverList(); 
}
Subject.prototype = {
    constructor:Subject,
    addObserver:function(observer){
        this.xxxState.add(observer);
    },
    notifyObserver:function(someState){
        this.xxxState.notify(someState);
    },
    removeObserver:function(observer){
       this.xxxState.remove(observer);
    }
};
var observer = new Observer();

var subject = new Subject();
subject.addObserver(observer);
subject.notifyObserver('this is test for change');
subject.removeObserver(observer);