zoukankan      html  css  js  c++  java
  • 观察者模式

    转载自:https://www.cnblogs.com/lovesong/p/5272752.html

    比较概念的解释是,目标和观察者是基类,目标提供维护观察者的一系列方法,观察者提供更新接口。具体观察者和具体目标继承各自的基类,然后具体观察者把自己注册到具体目标里,在具体目标发生变化时候,调度观察者的更新方法。

    比如有个“天气中心”的具体目标A,专门监听天气变化,而有个显示天气的界面的观察者B,B就把自己注册到A里,当A触发天气变化,就调度B的更新方法,并带上自己的上下文。

    //观察者列表
    function ObserverList(){
      this.observerList = [];
    }
    ObserverList.prototype.add = function( obj ){
      return this.observerList.push( obj );
    };
    ObserverList.prototype.count = function(){
      return this.observerList.length;
    };
    ObserverList.prototype.get = function( index ){
      if( index > -1 && index < this.observerList.length ){
        return this.observerList[ index ];
      }
    };
    ObserverList.prototype.indexOf = function( obj, startIndex ){
      var i = startIndex;
      while( i < this.observerList.length ){
        if( this.observerList[i] === obj ){
          return i;
        }
        i++;
      }
      return -1;
    };
    ObserverList.prototype.removeAt = function( index ){
      this.observerList.splice( index, 1 );
    };
    
    //目标
    function Subject(){
      this.observers = new ObserverList();
    }
    Subject.prototype.addObserver = function( observer ){
      this.observers.add( observer );
    };
    Subject.prototype.removeObserver = function( observer ){
      this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
    };
    Subject.prototype.notify = function( context ){
      var observerCount = this.observers.count();
      for(var i=0; i < observerCount; i++){
        this.observers.get(i).update( context );
      }
    };
    
    //观察者
    function Observer(){
      // ...
    }
    Observer.prototype.update=function(context){
    //....
    }
  • 相关阅读:
    希尔伯特空间(Hilbert Space)
    深度神经网络:特点、问题及解决
    深度神经网络:特点、问题及解决
    中英文对照 —— 手机 App/PC 端软件(系统)、互联网
    中英文对照 —— 手机 App/PC 端软件(系统)、互联网
    Opencv决策树分类器应用
    OpenCV实现朴素贝叶斯分类器诊断病情
    机器学习的实现(语言及库的选择)
    机器学习的实现(语言及库的选择)
    《The Economist》的阅读
  • 原文地址:https://www.cnblogs.com/ceceliahappycoding/p/10535624.html
Copyright © 2011-2022 走看看