JavaScript 设计模式--观察者模式 (Observer)

in JavaScript with 0 comment

观察者模式

1 ES5 function 写法

//定义发布者主体Subject对象
    function Subject() {
      //观察者数组
      this.observers = []
    }
    //添加观察者
    Subject.prototype.addObserver = function(observer) {
      this.observers.push(observer)
    }
    //删除观察者
    Subject.prototype.removeObserver = function(observer) {
      let index = this.observers.indexOf(observer)
      if(index > -1) {
        this.observers.splice(index, 1)
      }
    }
    //发布消息
    Subject.prototype.inFormObserver = function () {
       this.observers.forEach(observer => {
         observer.update()
       })
    }
    //观察者对象
    function Observer(name) {
       this.name = name
       this.update = function () { 
          console.log(name + ' 收到消息update...')
      }
    }
    //发布者主体
    let subject = new Subject()
    //订阅者1 
    let ob1 = new Observer('fans1')
    subject.addObserver(ob1)
    //订阅者2 
    let ob2 = new Observer('fans2')
    subject.addObserver(ob2)
    //发布消息
    subject.inFormObserver()

 2 ES6 class 写法
 
 class Subject {
        constructor() {
          this.observers = [];
        }
        addObserver(observer) {
          this.observers.push(observer);
        }
        removeObserver(observer) {
          let index = this.observers.indexOf(observer);
          if (index > -1) {
            this.observers.splice(index, 1);
          }
        }
        inFormObserver() {
          this.observers.forEach((observer) => {
            observer.update();
          });
        }
      }
      class Observer {
        constructor(name) {
          this.name = name;
        }
        update() {
          console.log(this.name + " 收到消息update...");
        }
      }
      let sub = new Subject()
      let ob1 = new Observer('fan1')
      sub.addObserver(ob1)
      let ob2 = new Observer('fan2')
      sub.addObserver(ob2)
      sub.inFormObserver()

评论已关闭.