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

  • 相关阅读:
    PS 修复画笔
    PS 魔棒工具、仿制图章
    PS选区的应用
    PS界面介绍
    火狐浏览器任务栏设置默认 隐私模式开启
    [CSS] Using inline-grid to gain easy control over gap and size
    [AWS] Presign url for S3
    [CSS] Customer focus / disabled style for select element
    [CSS] Using single grid-template-area and justify-self to select arrow down icon in select
    [CSS 3] Using CSS attribute selector
  • 原文地址:https://www.cnblogs.com/winner/p/1423870.html
Copyright © 2011-2022 走看看