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

  • 相关阅读:
    Idea tabs多行
    IDEA ,设置滚轮修改字体大小
    IDEA设置行号和方法间的分隔符
    设置超过指定 import 个数,改为*
    systemctl 命令完全指南
    如何让不断增加的目录只保留五个文件?
    Django框架重定向功能
    Django框架疫情信息平台!!!
    Django框架模板语法之for表单应用!!!
    Django框架模板语法之深度查询!!!
  • 原文地址:https://www.cnblogs.com/jjyjjyjjy/p/1420985.html
Copyright © 2020-2023  润新知