• 观察者+js 模式


    <script language="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");
    //-->
    </script>

  • 相关阅读:
    阅读笔记之梦断代码(二)
    php完成页面跳转并传值
    java 内部类
    阅读笔记之《程序员修炼之道从小工到专家》(一)
    java 反射机制
    微信的研究【转http://blog.csdn.net/chief1985/article/details/7902016】
    Java sending and receiving file (byte[]) over sockets
    Android音频实时传输与播放(四):源码下载(问题更新)【转】
    windows phone 游戏
    Android音频实时传输与播放(三):AMR硬编码与硬解码【转】
  • 原文地址:https://www.cnblogs.com/winner/p/1423870.html
Copyright © 2020-2023  润新知