前端设计模式-观察者模式(上)

观察者模式

  1. 发布&订阅

  2. 一对多

  3. 优点:更加解耦,支持广播通信

  4. 缺点:大量观察者,广播有性能问题

    // 主题对象
    class Subject {
      constructor() {
        this.state = {};
        this.observers = [];
      }
    
      getState() {
        return this.state;
      }
    
      setState(state) {
        this.state = state;
        this.notifyAllObservers();
      }
    
      notifyAllObservers() {
        this.observers.forEach(observer => {
          observer.update();
        });
      }
    
      attach(observer) {
        this.observers.push(observer);
      }
    
    }
    
    // 观察者
    class Observer {
      constructor(name, subject) {
        this.name = name;
        this.subject = subject;
        this.subject.attach(this);
      }
    
      update() {
        console.log(`${this.name} update, state: ${this.subject.getState()}`);
      }
    }
    
    // 测试
    
    let sub = new Subject();
    
    let ob1 = new Observer('Confidence', sub);
    let ob2 = new Observer('Java', sub);
    let ob3 = new Observer('NodeJs', sub);
    
    sub.setState(1);
    
  5. 场景

    • 网页事件绑定
      $('#btn').click(function() {
        console.log(1);
      });
      $('#btn').click(function() {
        console.log(2);
      });
      
    • Promise
      function loadImg() {
        const promise = new Promise((resolve, reject) => {
          var img = document.createElement('img');
          img.onload = function() {
            resolve(img);
          }
          img.onerror = function() {
            reject('图片加载失败);
          }
          img.src = 'https://....xxx.png';
        });
        return promise;
      }
      
      
      loadImg().then(res => {
        return res;
      }).then(res => {
        console.log(res);
      })
      
    • jQuery callbacks
      var callbacks = $.Callbacks();
      callbacks.add(function(info) {
        console.log('fn1', info);
      });
      callbacks.add(function(info) {
        console.log('fn2', info);
      });
      
      callbacks.fire('arg1');
      callbacks.fire('arg2');
      
    • nodejs自定义事件
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,731评论 0 3
  • 单例模式 适用场景:可能会在场景中使用到对象,但只有一个实例,加载时并不主动创建,需要时才创建 最常见的单例模式,...
    Obeing阅读 2,112评论 1 10
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,060评论 0 2
  • 一、观察者模式概述 +观察者模式又叫做发布-订阅模式观察者模式定义了一种一对多的依赖关系,让多个观察者对象同事监听...
    Mitchell阅读 254评论 0 0
  • 1. 概述 有时被称作发布/订阅模式,观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象...
    eb51589b1211阅读 402评论 0 0