首页 > 代码库 > 观察者模式

观察者模式

观察者模式具有以下组件

(1) Subject 目标: 维护一系列的观察者,方便添加或者删除观察者

(2) Observer 观察者 : 为那些在目标状态发生改变时需获取得通知的对象提供一个接口

(3) ConcreteSubject 具体目标 : 状态发生改变时,向observer发出通知,储存ConcreteObserver的状态

(4) ConcreteObserver 具体观察者 : 存储一个指向ConcreteSubject的引用,实现Observer的更新

    //----------- observer list    var ObservertionList = function () {        this.observerList = [];    };    ObservertionList.prototype.add = function (value) {        this.observerList.push(value);    };    ObservertionList.prototype.Get = function (index) {        //if(){   //do something        return this.observerList[index];        //}    };    ObservertionList.prototype.Count = function () {        return this.observerList.length;    };    var extend = function (obj, extension) {        for (var key in obj) {            extension[key] = obj[key];        }    };    //----------(1) subject    var Subject = function () {        this.observers = new ObservertionList();    };    Subject.prototype.addObserver = function (obj) {        this.observers.add(obj);    };    Subject.prototype.notify = function (index) {        //var len = this.observers.Count();        // for(var i=0;i<len;i++){        this.observers.Get(index).broadCast();        // }    };    var observations = [        {            Id: 1,            name: "Jackey",            age: 24,            skill: function () {                console.log("programming");            }        },        {            Id: 2,            name: "Cassi",            age: 23,            skill: function () {                console.log("cooking");            }        }    ];    //(2) observer    var broadCast = function () {        this.broadCast = function () {            console.log("broadCast to other");        };    };    var subject = new Subject();    for (var i = 0; i < observations.length; i++) {        extend(new broadCast(), observations[i]);        subject.addObserver(observations[i]);        subject.notify(i);    }    ;

 

观察者模式