javascript publish/subscribe or observer pattern

 定義javascript

定義一對多的對象封裝,目標對象狀態發生變化,它全部的接受者都會收到通知並作相應的更新。java

使用頻率:5/5 最高this

概要prototype

觀察者模式,也就是發佈者/訂閱者模式,當發佈者發佈一個通知的時候,訂閱者就會收到通知,並調用本身的更新方法,作些什麼事情。這種通知是單向的,只能由發佈者向訂閱者發佈通知。server

圖標說明對象

Diagram JavaScript Observer Design Pattern

示例代碼ip

      var Publisher = function () {        this.subscribers = [];      }      Publisher.prototype = {          constructor: Publisher,          addSubscriber: function(subscriber){            this.subscribers.push(subscriber);          },          removeSubscriber: function(subscriber){            var subscribers = this.subscribers,              len = subscribers.length,              i = 0;            for(; i < len; i++){              if (subscribers[i] === subscriber) {                delete subscribers[i];                break;              };            }          },          notifySubscriber: function(message){            var subscribers = this.subscribers,              len = subscribers.length,              i = 0;            for(; i< len; i++){              subscribers[i].receiveMessage(message);            }          }      };      var Subscriber = function(subscriberName, publisher){        this.name = subscriberName;        this.publisher = publisher;      };      Subscriber.prototype = {        constructor: Subscriber,        receiveMessage: function(message){          console.log('I am ' + this.name + ' I receive: ' + message);        }      };      var publisher = new Publisher();      var subUser_001 = new Subscriber('subUser_001', publisher);      var subUser_002 = new Subscriber('subUser_002', publisher);      var subUser_003 = new Subscriber('subUser_003', publisher);      publisher.addSubscriber(subUser_001);      publisher.addSubscriber(subUser_002);      publisher.addSubscriber(subUser_003);      publisher.notifySubscriber('百度推送新聞了');
相關文章
相關標籤/搜索