zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    javascript中的预编译问题
    五环
    两列布局
    定位以及z-index
    [vijos1234]口袋的天空<最小生成树>
    [讲解]prim算法<最小生成树>
    [noip模拟]B<构造>
    [JZOJ5343]健美猫<模拟>
    [noip模拟]心<并查集>
    [noip模拟]种花<快速幂+结论>
  • 原文地址:https://www.cnblogs.com/code-style/p/4235781.html
Copyright © 2011-2022 走看看