码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript的OOP编程2

时间:2015-01-20 13:29:27      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

我做了一个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

 

JavaScript的OOP编程2

标签:

原文地址:http://www.cnblogs.com/code-style/p/4235781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!