观察者+js 模式
<script language="JavaScript">
<!--
/*---------------------------
defined observer
----------------------------*/
function Observer()//观察者
{
}
Observer.prototype.update = function(context)//观察者方法
{
alert(context);
}
function ConcreteObserver()//具体观察者
{
Observer.call(this);
}
ConcreteObserver.prototype.update = function(context)//具体观察者方法
{
alert("ConcreteObserver response " + context);
}
/*---------------------------
defined ObserverCollection // 观察者集合
----------------------------*/
function ObserverCollection()// 观察者集合
{
this._observers_ = new Array(); //定义数组
}
ObserverCollection.prototype.add = function(observer) //定义数组添加方法
{
this._observers_.push(observer);
}
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 Subject(name)
{
this.name = name;
this._obs_ = new ObserverCollection();
}
Subject.prototype.add = function(ob) //添加观察者对象
{
if (ob.update)
{
this._obs_.add(ob);
}
}
Subject.prototype.nameChanged = function()
{
var ob;
for(var i=0; i < this._obs_.count(); i++)
{
ob = this._obs_.getAt(i);
ob.update(this.name);
}
};
Subject.prototype.setName = function(newName)
{
if (this.name != newName)
{
this.name = newName;
this.nameChanged();
}
}
var sub = new Subject("jjy");
sub.add(new Observer());
sub.add(new ConcreteObserver());
sub.setName("Jack");
sub.setName("HongYing");
//-->
</script>