1. 程式人生 > >javascript設計模式之觀察者模式(行為模式)

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!