javascript设计模式之观察者模式(行为模式)

javascript设计模式之观察者模式

js的设计模式分为创建型模式,结构型模式和行为模式

行为模式描述了对象之间的通信行为。

观察者模式又叫发布–订阅模式,是一种常见的行为模式。

下面是示例代码:

// obesever mode
var observer = {
  // add a subscriber
  addSubscribes:function (callback){
     
    if(typeof callback === 'function'){
      this.subscribes[this.subscribes.length] = callback;
    }
  },

  // remove a subscriber
  removeSubscribes:function (callback){
     
    for (var i = this.subscribes.length - 1; i >= 0; i--) {
      if(typeof this.subscribes[i] === callback){
        delete this.subscribes[i];
      }
    }
  },

  // publish event
  publish:function (what){
     
    for (var i = this.subscribes.length - 1; i >= 0; i--) {
      if(typeof this.subscribes[i] === 'function'){
        this.subscribes[i](what);
      }
    }
  },

  // turn an object into a observer
  make:function (o){
     
    for(var i in this){
      if(this.hasOwnProperty(i)){
        o[i] = this[i];
        o.subscribes = [];
      }
    }
  }
};

var blogger = {
  writeBlogPost:function (){
     
    var content = 'hello' + new Date();
    this.publish(content);
  }
};

var la_time = {
  newIssue:function (){
     
    var issue = 'Martians has landed on Earth!';
    this.publish(issue);
  }
};

observer.make(blogger);
observer.make(la_time);

var jack = {
  read:function (what){
     
    console.log('I have just read' + what);
  }
};

var jill = {
  learn:function (what){
     
    console.log('I also have read an new issue:' + what);
  }
};

blogger.addSubscribes(jack.read);
la_time.addSubscribes(jill.learn);
blogger.writeBlogPost();
la_time.newIssue();

下面是输出结果:

I have just readhelloTue May 02 2017 14:43:49 GMT+0800 (CST)
VM481517:63 I also have read an new issue:Martians has landed on Earth!

你可能感兴趣的:(前端技术,js面向对象编程指南学习笔记,javascript,设计模式)