观察者模式是一种设计模式,其中一个对象(Subject)维持一系列依赖于它(Observer)的对象,将有关状态的任何变更自动通知给它们。当一个目标需要告诉观察者发生了什么事情,它会向观察者广播一个通知。以下我们采用JavaScript来实现观察者模式。
- Subject(目标):维护一系列的观察者,方便添加或删除观察者。
- Observer(观察者):为那些在目标状态发生改变时需获得通知的对象提供一个更新接口。
首先,实现一个ObserList,用于存储一系列的Observer,代码如下:
function ObserverList() {
this.observerList = [];
}
ObserverList.prototype.Add = function(obj) {
return this.observerList.push(obj);
};
ObserverList.prototype.Empty = function() {
this.observerList = [];
};
ObserverList.prototype.Count = function() {
return this.observerList.length;
};
ObserverList.prototype.Get = function(index) {
if (index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
};
ObserverList.prototype.IndexOf = function(obj, startIndex) {
var i = startIndex, pointer = -1;
while (i < this.observerList.length) {
if (this.observerList[i] === obj) {
pointer = i;
break;
}
i++;
}
return pointer;
};
ObserverList.prototype.RemoveIndexAt = function(index) {
if (index > -1 && index < this.observerList.length) {
this.observerList.splice(index, 1);
}
};
接着,实现Observer,代码如下:
function Observer() {
this.id = Math.floor(Math.random() * 100);
}
Observer.prototype.Update = function(value) {
console.log(value + this.id);
};