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

  • 相关阅读:
    DATA_PUMP_DIR impdp 指定导出目录
    MasScan
    VMWare:vSphere6 企业版参考序列号
    ORA-12519: TNS:no appropriate service handler found 解决
    百度IOT
    IPMI远程管理一点记录
    关于parallel(并行)的几个基本常识
    hdu 4811 数学 不难
    关于i++ 和 ++i
    sqlplus中怎么将你全部的操作和结果记录保存到你指定的文件里
  • 原文地址:https://www.cnblogs.com/jjyjjyjjy/p/1420985.html
Copyright © 2020-2023  润新知