All files / src analyzer-factory.js

100% Statements 22/22
100% Branches 6/6
100% Functions 4/4
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82            1x 1x 1x 1x 1x           1x                         12x   12x 48x 480x 18x         12x 55x   12x                 8x             8x 8x 1x     7x                 3x 3x             1x  
/**
 * 工厂模式(Factory Pattern)
 * 
 * 根据问题类型自动创建对应的分析器
 */
 
const { FirstPrincipleAnalyzer } = require('./template-method');
const { TechnicalStrategy } = require('./strategies/technical-strategy');
const { BusinessStrategy } = require('./strategies/business-strategy');
const { LifeStrategy } = require('./strategies/life-strategy');
const { AcademicStrategy } = require('./strategies/academic-strategy');
 
class AnalyzerFactory {
  /**
   * 问题类型关键词映射
   */
  static KEYWORD_MAP = {
    technical: ['技术', '架构', '系统', '代码', '开发', '软件', '平台', 'API', '数据库', '性能'],
    business: ['商业', '市场', '产品', '盈利', '竞争', '投资', '创业', '增长', '用户', '收入'],
    life: ['人生', '职业', '选择', '工作', '生活', '家庭', '健康', '学习', '成长', '幸福'],
    academic: ['研究', '学术', '论文', '理论', '实验', '数据', '文献', '期刊', '学科', '知识']
  };
 
  /**
   * 根据问题文本自动检测类型
   * @param {string} problem - 问题描述
   * @returns {string} 类型
   */
  static detectType(problem) {
    const scores = { technical: 0, business: 0, life: 0, academic: 0 };
    
    for (const [type, keywords] of Object.entries(this.KEYWORD_MAP)) {
      for (const keyword of keywords) {
        if (problem.includes(keyword)) {
          scores[type]++;
        }
      }
    }
 
    const maxType = Object.entries(scores)
      .sort((a, b) => b[1] - a[1])[0];
    
    return maxType[1] > 0 ? maxType[0] : 'technical'; // 默认技术类
  }
 
  /**
   * 创建分析器
   * @param {string} type - 类型(technical/business/life/academic)
   * @returns {FirstPrincipleAnalyzer}
   */
  static createAnalyzer(type) {
    const strategies = {
      technical: TechnicalStrategy,
      business: BusinessStrategy,
      life: LifeStrategy,
      academic: AcademicStrategy
    };
 
    const StrategyClass = strategies[type];
    if (!StrategyClass) {
      throw new Error(`Unknown strategy type: ${type}`);
    }
 
    return new FirstPrincipleAnalyzer(new StrategyClass());
  }
 
  /**
   * 智能创建分析器(自动检测类型)
   * @param {string} problem - 问题描述
   * @returns {{analyzer: FirstPrincipleAnalyzer, detectedType: string}}
   */
  static createSmartAnalyzer(problem) {
    const detectedType = this.detectType(problem);
    return {
      analyzer: this.createAnalyzer(detectedType),
      detectedType
    };
  }
}
 
module.exports = { AnalyzerFactory };