工具函数 · 65/107
1. 抽象工厂模式 2. Adapter Pattern 3. Adapter Pattern 4. 实现一个支持柯里化的 add 函数 5. 计算两个数组的交集 6. 数组中的数据根据key去重 7. 实现一个add方法完成两个大数相加 8. 大数相加 9. bind、call、apply 的区别与实现 10. Bridge Pattern 11. Builder Pattern 12. 实现一个管理本地缓存过期的函数 13. 缓存代理 14. 转化为驼峰命名 15. 实现 (5).add(3).minus(2) 功能 16. 咖啡机进阶优化 17. 咖啡机状态管理 18. 常用设计模式总结 19. 咖啡机状态切换机制 20. 查找数组公共前缀(美团) 21. 实现一个compose函数 22. 并发请求调度器 23. 组合模式 24. 实现 console.log 代理方法 25. Decorator Pattern 26. 实现防抖和节流 27. 实现一个JS函数柯里化 28. 实现防抖函数(debounce) 29. Decorator Pattern 30. 手写深度比较isEqual 31. 消除 if-else 条件判断 32. 修改嵌套层级很深对象的 key 33. 设计模式应用 34. 验证是否是邮箱 35. 实现发布订阅模式 36. 外观模式 37. Facade Pattern 38. Factory Pattern 39. 工厂模式 40. 工厂模式实现 41. Flyweight Pattern 42. 前端常用设计模式与场景 43. 提取对象中所有value大于2的键值对 44. 用正则实现根据name获取cookie中的值 45. 获取今天的日期 46. ES6 之前的迭代器模式 47. 实现 getValue/setValue 函数来获取path对应的值 48. 验证是否是身份证 49. 迭代器模式 50. jQuery slideUp 动画队列堆积问题 51. 实现一个JSON.parse 52. 实现 LazyMan 任务队列 53. 实现一个JSON.stringify 54. 实现lodash的chunk方法--数组按指定长度拆分 55. 字符串最长的不重复子串 56. LRU 缓存算法 57. 查找字符串中出现最多的字符和个数 58. new 操作符的实现原理 59. 中介者模式 60. 中介者模式 61. 对象数组如何去重 62. 千分位格式化 63. 实现观察者模式 64. 观察者模式实例 65. 观察者模式 66. 实现观察者模式 67. 实现 padStart() 和 padEnd() 的 Polyfill 68. 判断是否是电话号码 69. Proxy Pattern 70. 代理模式:婚介所 71. Proxy Pattern 72. 代理模式 73. 实现上拉加载和下拉刷新 74. 生成随机数组并排序 75. 大文件断点续传实现 76. 使用 setInterval 模拟实现 setTimeout 77. 重构询价逻辑 78. 实现一个简单的路由 79. setTimeout 模拟实现 setInterval 80. RGB 转 Hex 颜色转换 81. setTimeout与setInterval实现 82. Simple Factory Pattern 83. 实现单例模式 84. 实现一个 sleep 函数 85. 状态模式 86. State Pattern 87. 策略模式 88. Strategy Pattern 89. Storage 单例封装 90. 策略模式 91. 计算字符串字节长度 92. 字符串压缩算法实现 93. 字符串查找 94. 字符串去除前后空格 95. 实现模板引擎 96. 实现千位分隔符 97. 实现模板字符串解析功能 98. 实现一个函数判断数据类型 99. Promise 实现红绿灯交替 100. 实现节流函数(throttle) 101. 从指定数据源生成长度为 n 的不重复随机数组 102. 解析 URL Params 为对象 103. URL 验证 104. 判断括号字符串是否有效 105. 虚拟代理 106. 访问者模式 107. 版本号排序的方法

观察者模式

实现观察者模式,理解发布-订阅机制

问题

实现观察者模式,让多个观察者监听一个主题对象,当主题状态变化时自动通知所有观察者。

解答

基础实现

// 主题(被观察者)
class Subject {
  constructor() {
    this.observers = []
  }

  // 添加观察者
  addObserver(observer) {
    this.observers.push(observer)
  }

  // 移除观察者
  removeObserver(observer) {
    this.observers = this.observers.filter(obs => obs !== observer)
  }

  // 通知所有观察者
  notify(data) {
    this.observers.forEach(observer => observer.update(data))
  }
}

// 观察者
class Observer {
  constructor(name) {
    this.name = name
  }

  update(data) {
    console.log(`${this.name} 收到通知:`, data)
  }
}

// 使用
const subject = new Subject()

const observer1 = new Observer('观察者1')
const observer2 = new Observer('观察者2')

subject.addObserver(observer1)
subject.addObserver(observer2)

subject.notify({ message: '状态更新了' })
// 观察者1 收到通知: { message: '状态更新了' }
// 观察者2 收到通知: { message: '状态更新了' }

subject.removeObserver(observer1)
subject.notify({ message: '再次更新' })
// 观察者2 收到通知: { message: '再次更新' }

EventEmitter 实现

class EventEmitter {
  constructor() {
    this.events = {}
  }

  // 订阅事件
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
    return this
  }

  // 取消订阅
  off(event, callback) {
    if (!this.events[event]) return this
    this.events[event] = this.events[event].filter(cb => cb !== callback)
    return this
  }

  // 触发事件
  emit(event, ...args) {
    if (!this.events[event]) return this
    this.events[event].forEach(callback => callback(...args))
    return this
  }

  // 只订阅一次
  once(event, callback) {
    const wrapper = (...args) => {
      callback(...args)
      this.off(event, wrapper)
    }
    this.on(event, wrapper)
    return this
  }
}

// 使用
const emitter = new EventEmitter()

emitter.on('login', user => {
  console.log(`${user} 登录了`)
})

emitter.once('firstVisit', () => {
  console.log('首次访问,显示引导')
})

emitter.emit('login', '张三')  // 张三 登录了
emitter.emit('firstVisit')     // 首次访问,显示引导
emitter.emit('firstVisit')     // 无输出,因为用的 once

实际应用:数据绑定

// 简单的响应式数据
function reactive(obj, callback) {
  return new Proxy(obj, {
    set(target, key, value) {
      const oldValue = target[key]
      target[key] = value
      // 值变化时通知
      if (oldValue !== value) {
        callback(key, value, oldValue)
      }
      return true
    }
  })
}

// 使用
const state = reactive({ count: 0 }, (key, newVal, oldVal) => {
  console.log(`${key}: ${oldVal} -> ${newVal}`)
})

state.count = 1  // count: 0 -> 1
state.count = 2  // count: 1 -> 2

关键点

  • 一对多关系:一个主题对应多个观察者,解耦发布者和订阅者
  • 主动推送:状态变化时主动通知,观察者无需轮询
  • EventEmitter:Node.js 和浏览器中广泛使用的事件机制
  • 应用场景:DOM 事件、Vue 响应式、Redux 状态管理、WebSocket 消息处理
  • 与发布订阅区别:观察者模式是直接通知,发布订阅有中间调度中心