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");

posted @ 2009-03-24 23:28  十三  阅读(227)  评论(0编辑  收藏  举报