技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

JavaScript的OOP编程2

我做了一个observer的设计模式实现

version1

// --------------------------------------------------
function Subject(){}
Subject.prototype.add = function(obj)
{
    if(typeof(obj.update) === "function")
    {
        this.objects.push(obj);
        return true;
    }
    return false;
}

Subject.prototype.notify = function(subject)
{
    for(var i in this.objects)
    {
        obj = this.objects[i];
        obj.update(subject);
    }
}

// --------------------------------------------------

function Subject1()
{
    Subject.call(this);
    this.objects = new Array();
    this.message = "hello";
}

Subject1.prototype = new Subject()
Subject1.prototype.update = function(s)
{
    if (s != null)
        this.message = s;
    this.notify(this);
}

// --------------------------------------------------
function Observer(){}
Observer.prototype.update = function(subject)
{
    alert(subject.message);
}


// --------------------------------------------------
var subject = new Subject1();
var observer = new Observer();

subject.add(observer);
subject.update();
subject.update("same world");

version2

 

posted on 2015-01-20 12:52  codestyle  阅读(225)  评论(0编辑  收藏  举报