观察者模式
字数: 0

基本概念

Observer pattern: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
notion image
notion image

实现代码

发布者

或者称为主题 (subject)

订阅者

该接口至少应声明一个 update 方法

具体发布者

具体订阅者

测试类

Q & A

What are the key benefits of the observer pattern?
  • The subject and its registered observers are making a loosely coupled system. They do not need to know each other explicitly.
  • You can independently add or remove observers at any time. And there is no modification is required in subjects.
What are the key challenges associated with an observer pattern?
  • The order of notification is not dependable.
  • Memory leak is the greatest concern when you deal with any event-based mechanism. An automatic garbage collector may not always help you in this context.
    • You can consider such a case where the deregister/unregister operations are not performed properly.

Java 的 JVM 引入了垃圾回收机制,垃圾回收器会自动回收不再使用的对象。JVM 是使用引用计数法和可达性分析算法来判断对象是否是不再使用的对象,本质都是判断一个对象是否还被引用。内存泄漏意味着即使这些对象已经无用,它们仍然占据着宝贵的内存资源。
notion image
此外还有以下常见的情景:
  • 各种连接:如数据库连接、网络连接和 I/O 连接等。
  • 变量不合理的作用域:如一个变量的定义的作用范围大于其使用范围,或者没有及时地把对象设置为 null。

具体应用

Vue.js

  • Vue 的响应式系统:当你在 Vue 实例中定义一个数据属性时,Vue 会通过Object.defineProperty 将这些属性转换为 getter/setter,并收集依赖(即谁在观察这个属性)。当属性变化时,Vue 知道哪些依赖需要被通知(即哪些地方使用了这个属性),从而触发视图更新或执行其他响应式操作。
  • 虚拟 DOM:Vue 的响应式系统与其虚拟 DOM 系统协同工作。当数据变化触发更新时,Vue 生成一个新的虚拟 DOM 树,并与之前的树进行比较,计算出需要在真实DOM 上做的最小更改,然后执行这些更改。

  • data 中的 message 是被观察的数据(相当于发布者)
  • computed 属性中的 reversedMessage依赖于 message。当 更新时,也会自动更新(相当于观察者)。
notion image
  • 当点击按钮时,reverseMessage 方法会被调用,它更新 message 的值。由于 message 发生变化,Vue的响应式系统会通知所有依赖于 message 的观察者,即更新 reversedMessage,并且更新 DOM 中相关的绑定。

React 使用一种称为“状态提升”Lifting state up的模式来处理跨组件的状态管理。当状态在 React 组件中发生变化时,React 会重新渲染这个组件以及它的子组件。
2023 - 2026