工具函数 · 42/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. 版本号排序的方法

前端常用设计模式与场景

单例、观察者、策略、代理等设计模式在前端的实现与应用

问题

前端开发中常用哪些设计模式?各自的使用场景是什么?

解答

1. 单例模式

确保一个类只有一个实例。

// 单例模式
class Store {
  static instance = null
  
  constructor() {
    if (Store.instance) {
      return Store.instance
    }
    this.state = {}
    Store.instance = this
  }
  
  setState(key, value) {
    this.state[key] = value
  }
  
  getState(key) {
    return this.state[key]
  }
}

// 使用
const store1 = new Store()
const store2 = new Store()
console.log(store1 === store2) // true

场景:全局状态管理、弹窗组件、登录框

2. 发布订阅模式

对象间一对多的依赖关系,状态变化时通知所有订阅者。

class EventEmitter {
  constructor() {
    this.events = {}
  }
  
  // 订阅
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
    return this
  }
  
  // 发布
  emit(event, ...args) {
    const callbacks = this.events[event]
    if (callbacks) {
      callbacks.forEach(cb => cb(...args))
    }
    return this
  }
  
  // 取消订阅
  off(event, callback) {
    const callbacks = this.events[event]
    if (callbacks) {
      this.events[event] = callbacks.filter(cb => cb !== callback)
    }
    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.emit('login', '张三') // 张三 登录了

场景:组件通信、事件总线、Vue 的 $emit

3. 策略模式

定义一系列算法,把它们封装起来,使它们可以互相替换。

// 表单验证策略
const strategies = {
  required(value, message) {
    return value.trim() === '' ? message : ''
  },
  minLength(value, length, message) {
    return value.length < length ? message : ''
  },
  mobile(value, message) {
    return !/^1[3-9]\d{9}$/.test(value) ? message : ''
  },
  email(value, message) {
    return !/^\w+@\w+\.\w+$/.test(value) ? message : ''
  }
}

// 验证器
class Validator {
  constructor() {
    this.rules = []
  }
  
  add(value, rule, ...args) {
    this.rules.push(() => strategies[rule](value, ...args))
    return this
  }
  
  validate() {
    for (const rule of this.rules) {
      const error = rule()
      if (error) return error
    }
    return ''
  }
}

// 使用
const validator = new Validator()
validator
  .add('', 'required', '用户名不能为空')
  .add('abc', 'minLength', 6, '用户名至少6位')

console.log(validator.validate()) // 用户名不能为空

场景:表单验证、支付方式选择、不同权限的操作

4. 代理模式

为对象提供一个代理,控制对原对象的访问。

// 图片懒加载代理
const lazyLoadImage = (function() {
  const img = document.createElement('img')
  
  return {
    setSrc(node, src) {
      // 先显示占位图
      node.src = 'loading.gif'
      // 加载真实图片
      img.onload = () => {
        node.src = src
      }
      img.src = src
    }
  }
})()

// 缓存代理
const memoize = (fn) => {
  const cache = new Map()
  
  return function(...args) {
    const key = JSON.stringify(args)
    if (cache.has(key)) {
      return cache.get(key)
    }
    const result = fn.apply(this, args)
    cache.set(key, result)
    return result
  }
}

// 使用
const fibonacci = memoize(n => {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
})

console.log(fibonacci(40)) // 快速计算

场景:图片懒加载、缓存计算结果、Vue3 响应式(Proxy)

5. 装饰器模式

动态地给对象添加额外的职责。

// 函数装饰器 - 添加日志
function withLog(fn) {
  return function(...args) {
    console.log(`调用 ${fn.name},参数:`, args)
    const result = fn.apply(this, args)
    console.log(`返回值:`, result)
    return result
  }
}

// 函数装饰器 - 防抖
function debounce(fn, delay) {
  let timer = null
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 使用
const add = (a, b) => a + b
const loggedAdd = withLog(add)
loggedAdd(1, 2)
// 调用 add,参数: [1, 2]
// 返回值: 3

// React HOC 也是装饰器模式
function withAuth(Component) {
  return function AuthComponent(props) {
    const isLogin = checkLogin()
    if (!isLogin) {
      return <Login />
    }
    return <Component {...props} />
  }
}

场景:React HOC、防抖节流、日志记录、权限校验

6. 工厂模式

封装创建对象的逻辑,不暴露具体实现。

// 简单工厂
class Button {
  constructor(type) {
    this.type = type
  }
  render() {
    return `<button class="${this.type}">按钮</button>`
  }
}

class Input {
  constructor(type) {
    this.type = type
  }
  render() {
    return `<input type="${this.type}" />`
  }
}

// 工厂函数
function createComponent(type, config) {
  switch(type) {
    case 'button':
      return new Button(config.style)
    case 'input':
      return new Input(config.inputType)
    default:
      throw new Error('未知组件类型')
  }
}

// 使用
const btn = createComponent('button', { style: 'primary' })
const input = createComponent('input', { inputType: 'text' })

场景:创建组件实例、根据配置生成不同对象

关键点

  • 单例模式:全局唯一实例,适合状态管理、弹窗
  • 发布订阅:解耦组件通信,是事件系统的基础
  • 策略模式:消除 if-else,算法可替换,适合表单验证
  • 代理模式:控制访问,适合懒加载、缓存、Vue3 响应式
  • 装饰器模式:不修改原函数增强功能,适合 HOC、防抖节流
  • 工厂模式:封装创建逻辑,适合根据配置创建不同实例