浅析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   }

 

三、优缺点浅析

  观察者和被观察者之间耦合小,二者没有十分紧密的联系,能够十分方便地扩展自身,但当观察者增多的时候性能会有下降。

转载于:https://www.cnblogs.com/prinny/p/9830205.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值