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

Flyweight Pattern

享元模式的实现与应用场景

问题

什么是享元模式?如何在 JavaScript 中实现?

解答

享元模式通过共享对象来减少内存占用,将对象的状态分为:

  • 内部状态:可共享,存储在享元对象中
  • 外部状态:不可共享,由客户端传入

基本实现

// 享元类 - 存储内部状态(可共享)
class Flyweight {
  constructor(sharedState) {
    this.sharedState = sharedState;
  }

  operation(uniqueState) {
    const s = JSON.stringify(this.sharedState);
    const u = JSON.stringify(uniqueState);
    console.log(`Flyweight: 共享(${s}) 独有(${u})`);
  }
}

// 享元工厂 - 管理享元对象的创建和复用
class FlyweightFactory {
  constructor() {
    this.flyweights = {};
  }

  getKey(state) {
    return state.join('_');
  }

  getFlyweight(sharedState) {
    const key = this.getKey(sharedState);

    if (!this.flyweights[key]) {
      console.log('创建新享元:', key);
      this.flyweights[key] = new Flyweight(sharedState);
    } else {
      console.log('复用已有享元:', key);
    }

    return this.flyweights[key];
  }

  getCount() {
    return Object.keys(this.flyweights).length;
  }
}

// 使用
const factory = new FlyweightFactory();

// 相同内部状态会复用同一个对象
const fw1 = factory.getFlyweight(['Toyota', 'Camry']);
const fw2 = factory.getFlyweight(['Toyota', 'Camry']); // 复用
const fw3 = factory.getFlyweight(['BMW', 'X5']);

fw1.operation({ owner: 'Alice', plates: 'ABC123' });
fw2.operation({ owner: 'Bob', plates: 'XYZ789' });

console.log('享元对象总数:', factory.getCount()); // 2

实际应用:文本编辑器字符渲染

// 字符享元 - 共享字体样式
class CharacterFlyweight {
  constructor(font, size, color) {
    this.font = font;
    this.size = size;
    this.color = color;
  }

  render(char, x, y) {
    console.log(`渲染 "${char}" 在 (${x},${y}) 样式: ${this.font}/${this.size}/${this.color}`);
  }
}

// 字符享元工厂
class CharacterFactory {
  constructor() {
    this.cache = new Map();
  }

  getCharacter(font, size, color) {
    const key = `${font}-${size}-${color}`;

    if (!this.cache.has(key)) {
      this.cache.set(key, new CharacterFlyweight(font, size, color));
    }

    return this.cache.get(key);
  }
}

// 文档类 - 管理字符
class Document {
  constructor() {
    this.characters = [];
    this.factory = new CharacterFactory();
  }

  addCharacter(char, font, size, color, x, y) {
    const flyweight = this.factory.getCharacter(font, size, color);
    // 只存储字符和位置(外部状态)
    this.characters.push({ char, flyweight, x, y });
  }

  render() {
    this.characters.forEach(({ char, flyweight, x, y }) => {
      flyweight.render(char, x, y);
    });
  }
}

// 使用
const doc = new Document();

// 1000 个字符,但样式对象只有少数几个
for (let i = 0; i < 1000; i++) {
  doc.addCharacter(
    String.fromCharCode(65 + (i % 26)),
    'Arial',
    i % 2 === 0 ? '12px' : '14px',
    i % 3 === 0 ? 'red' : 'black',
    i * 10,
    Math.floor(i / 100) * 20
  );
}

console.log('字符数:', doc.characters.length); // 1000
console.log('享元对象数:', doc.factory.cache.size); // 4 (2种大小 × 2种颜色)

DOM 事件委托(享元思想)

// 不使用享元:每个按钮绑定事件
document.querySelectorAll('.btn').forEach(btn => {
  btn.addEventListener('click', handleClick); // 创建多个处理函数
});

// 使用享元:事件委托
document.getElementById('container').addEventListener('click', (e) => {
  if (e.target.matches('.btn')) {
    // 共享一个处理函数,通过 e.target 获取外部状态
    const id = e.target.dataset.id;
    handleClick(id);
  }
});

关键点

  • 内部状态共享:多个对象共享相同的内部数据,减少对象数量
  • 外部状态分离:不可共享的数据由客户端维护和传入
  • 工厂模式配合:通过工厂管理享元对象的创建和缓存
  • 适用场景:大量相似对象、对象的大部分状态可外部化、内存敏感的应用
  • 前端应用:事件委托、对象池、虚拟列表中的 DOM 复用