淺析vue項目中的觀察者模式


一、什么是觀察者模式

  定義

    “觀察者模式是軟件設計模式的一種。在此種模式中,一個目標對象管理所有相依於它的觀察者對象,並且在它本身的狀態改變時主動發出通知。這通常透過呼叫各觀察者所提供的方法來實現。此種模式通常被用來實時事件處理系統。”    -------------Wikipedia

  

 

  作用

  • 當抽象個體有兩個互相依賴的層面時。封裝這些層面在單獨的對象內將可允許程序員單獨地去變更與重復使用這些對象,而不會產生兩者之間交互的問題。
  • 當其中一個對象的變更會影響其他對象,卻又不知道多少對象必須被同時變更時。
  • 當對象應該有能力通知其他對象,又不應該知道其他對象的實做細節時。

二、vue中觀察者模式淺析

  以下代碼為vue中dep和watcher的觀察者模式示例,watcher訂閱dep,dep通知watcher執行update。

  dep.js

 1 /**
 2  * A dep is an observable that can have multiple
 3  * directives subscribing to it.
 4  */
 5 export default class Dep {
 6   static target: ?Watcher;
 7   id: number;
 8   subs: Array<Watcher>;
 9 
10   constructor () {
11     this.id = uid++
12     this.subs = []
13   }
14   
15   addSub (sub: Watcher) {        //添加訂閱者
16     this.subs.push(sub)
17   }
18 
19   removeSub (sub: Watcher) {      //刪除訂閱者
20     remove(this.subs, sub)
21   }
22 
23   depend () {
24     if (Dep.target) {
25       Dep.target.addDep(this)
26     }
27   }
28 
29   notify () {               //通知訂閱者
30     // stabilize the subscriber list first
31     const subs = this.subs.slice()
32     if (process.env.NODE_ENV !== 'production' && !config.async) {
33       // subs aren't sorted in scheduler if not running async
34       // we need to sort them now to make sure they fire in correct
35       // order
36       subs.sort((a, b) => a.id - b.id)
37     }
38     for (let i = 0, l = subs.length; i < l; i++) {
39       subs[i].update()         //訂閱者update方法
40     }
41   }
42 }

 

  watcher.js中的update方法

 1 /**
 2    * Subscriber interface.
 3    * Will be called when a dependency changes.
 4    */
 5   update () {                                  //watcher作為訂閱者的update方法
 6     /* istanbul ignore else */
 7     if (this.lazy) {
 8       this.dirty = true
 9     } else if (this.sync) {
10       this.run()
11     } else {
12       queueWatcher(this)
13     }
14   }

 

三、優缺點淺析

  觀察者和被觀察者之間耦合小,二者沒有十分緊密的聯系,能夠十分方便地擴展自身,但當觀察者增多的時候性能會有下降。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM