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

访问者模式

实现访问者模式,分离数据结构与操作

问题

什么是访问者模式?如何在 JavaScript 中实现?

解答

访问者模式将数据结构与作用于结构上的操作分离,使得可以在不修改数据结构的前提下添加新的操作。

基本实现

// 元素接口 - 接受访问者
class Element {
  accept(visitor) {
    throw new Error('子类必须实现 accept 方法');
  }
}

// 具体元素:文章
class Article extends Element {
  constructor(title, wordCount) {
    super();
    this.title = title;
    this.wordCount = wordCount;
  }

  accept(visitor) {
    visitor.visitArticle(this);
  }
}

// 具体元素:视频
class Video extends Element {
  constructor(title, duration) {
    super();
    this.title = title;
    this.duration = duration; // 分钟
  }

  accept(visitor) {
    visitor.visitVideo(this);
  }
}

// 访问者接口
class Visitor {
  visitArticle(article) {}
  visitVideo(video) {}
}

// 具体访问者:统计访问者
class StatsVisitor extends Visitor {
  constructor() {
    super();
    this.totalWords = 0;
    this.totalDuration = 0;
  }

  visitArticle(article) {
    this.totalWords += article.wordCount;
    console.log(`统计文章: ${article.title}, ${article.wordCount} 字`);
  }

  visitVideo(video) {
    this.totalDuration += video.duration;
    console.log(`统计视频: ${video.title}, ${video.duration} 分钟`);
  }

  getStats() {
    return {
      totalWords: this.totalWords,
      totalDuration: this.totalDuration
    };
  }
}

// 具体访问者:导出访问者
class ExportVisitor extends Visitor {
  constructor() {
    super();
    this.result = [];
  }

  visitArticle(article) {
    this.result.push({
      type: 'article',
      title: article.title,
      readTime: Math.ceil(article.wordCount / 300) + ' 分钟'
    });
  }

  visitVideo(video) {
    this.result.push({
      type: 'video',
      title: video.title,
      duration: video.duration + ' 分钟'
    });
  }

  getResult() {
    return this.result;
  }
}

// 对象结构 - 管理元素集合
class ContentLibrary {
  constructor() {
    this.elements = [];
  }

  add(element) {
    this.elements.push(element);
  }

  // 接受访问者遍历所有元素
  accept(visitor) {
    this.elements.forEach(element => element.accept(visitor));
  }
}

// 使用示例
const library = new ContentLibrary();
library.add(new Article('JavaScript 基础', 1500));
library.add(new Article('React 入门', 2000));
library.add(new Video('Vue 教程', 30));
library.add(new Video('Node.js 实战', 45));

// 使用统计访问者
const statsVisitor = new StatsVisitor();
library.accept(statsVisitor);
console.log(statsVisitor.getStats());
// { totalWords: 3500, totalDuration: 75 }

// 使用导出访问者 - 无需修改元素类
const exportVisitor = new ExportVisitor();
library.accept(exportVisitor);
console.log(exportVisitor.getResult());

实际应用:AST 遍历

// 简化的 AST 节点
class NumberNode {
  constructor(value) {
    this.value = value;
  }

  accept(visitor) {
    return visitor.visitNumber(this);
  }
}

class BinaryNode {
  constructor(operator, left, right) {
    this.operator = operator;
    this.left = left;
    this.right = right;
  }

  accept(visitor) {
    return visitor.visitBinary(this);
  }
}

// 计算访问者
class CalculateVisitor {
  visitNumber(node) {
    return node.value;
  }

  visitBinary(node) {
    const left = node.left.accept(this);
    const right = node.right.accept(this);

    switch (node.operator) {
      case '+': return left + right;
      case '-': return left - right;
      case '*': return left * right;
      case '/': return left / right;
    }
  }
}

// 打印访问者
class PrintVisitor {
  visitNumber(node) {
    return String(node.value);
  }

  visitBinary(node) {
    const left = node.left.accept(this);
    const right = node.right.accept(this);
    return `(${left} ${node.operator} ${right})`;
  }
}

// 构建 AST: (1 + 2) * 3
const ast = new BinaryNode(
  '*',
  new BinaryNode('+', new NumberNode(1), new NumberNode(2)),
  new NumberNode(3)
);

const calculator = new CalculateVisitor();
const printer = new PrintVisitor();

console.log(ast.accept(printer));     // ((1 + 2) * 3)
console.log(ast.accept(calculator));  // 9

函数式实现

// 更简洁的函数式写法
const createVisitor = (handlers) => ({
  visit(node) {
    const handler = handlers[node.type];
    if (!handler) {
      throw new Error(`未知节点类型: ${node.type}`);
    }
    return handler(node, this);
  }
});

// 节点定义
const num = (value) => ({ type: 'number', value });
const binary = (op, left, right) => ({ type: 'binary', op, left, right });

// 计算访问者
const calcVisitor = createVisitor({
  number: (node) => node.value,
  binary: (node, visitor) => {
    const l = visitor.visit(node.left);
    const r = visitor.visit(node.right);
    const ops = { '+': (a, b) => a + b, '*': (a, b) => a * b };
    return ops[node.op](l, r);
  }
});

// 使用
const expr = binary('+', num(1), binary('*', num(2), num(3)));
console.log(calcVisitor.visit(expr)); // 7

关键点

  • 双重分派:通过 acceptvisit 两次调用确定具体操作
  • 开闭原则:添加新操作只需新增访问者,无需修改元素类
  • 适用场景:对象结构稳定但操作经常变化,如 AST 处理、DOM 遍历
  • 缺点:添加新元素类型需要修改所有访问者
  • 前端应用:Babel 插件、ESLint 规则、编译器实现