萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Switch Case 實戰模式:表單題型處理邏輯重構指南

業務場景

在線考試系統中,根據題目類型 (單選、多選、填空、問答等) 執行不同的答案保存、計分、統計邏輯。

原始 Switch 結構分析


switch (objNameType) {
  case 'PD':      // 判斷題
  case 'DANX':    // 單選題
  case 'PP':      // 匹配題
    // 相似邏輯:獲取 ID、加載用戶答案、統計未答題數
    break;
  case 'text':    // 填空題
  case 'textarea': // 問答題
    // 文本值處理、空值清理、答題數增減
    break;
  case 'checkbox': // 多選題
    // 複雜:值拼接、部分選中、全清空邏輯
    break;
  default:
    return;
}

重構策略:策略模式替代 Switch

1. 定義統一接口


class AnswerHandler {
  constructor(exam, userData, stats) {
    this.exam = exam;
    this.userData = userData;
    this.stats = stats; // qNoTotalD, qIdNoStr 等統計對象
  }
  
  handle(obj) { throw new Error('Must implement'); }
  
  // 共用工具方法
  getTempGroupId(obj) {
    return obj.id.substr(0, obj.id.indexOf('_'));
  }
  
  incrementStat(obj) {
    const tgId = this.getTempGroupId(obj);
    this.stats.qNoTotalD[this.stats.qIdNoStr[tgId]]++;
  }
  
  decrementStat(obj) {
    const tgId = this.getTempGroupId(obj);
    this.stats.qNoTotalD[this.stats.qIdNoStr[tgId]]--;
  }
}

2. 具體策略實現


// 選擇類題型基類
class ChoiceHandler extends AnswerHandler {
  handle(obj) {
    const id = obj.id;
    const loadVUD = this.userData.load(this.exam, id);
    if (!loadVUD) this.incrementStat(obj);
  }
}

// 文本類題型
class TextHandler extends AnswerHandler {
  handle(obj) {
    const id = `text_${obj.id}`;
    const value = obj.value;
    const loadVUD = this.userData.load(this.exam, id);
    
    if (!loadVUD) {
      if (value) this.incrementStat(obj);
    } else {
      if (!value) {
        this.userData.remove(this.exam, id);
        this.decrementStat(obj);
      }
    }
  }
}

// 多選題型
class CheckboxHandler extends AnswerHandler {
  handle(obj) {
    const key = `checkbox_${obj.id.substr(0, obj.id.lastIndexOf('_'))}`;
    let valueUD = this.userData.load(this.exam, key);
    const checked = obj.checked;
    
    if (!valueUD) {
      if (checked) {
        this.userData.save(this.exam, key, obj.id);
        this.incrementStat(obj);
      }
    } else {
      const values = valueUD.split(',');
      const idx = values.indexOf(obj.id);
      if (checked && idx === -1) {
        values.push(obj.id);
        this.userData.save(this.exam, key, values.join(','));
      } else if (!checked && idx !== -1) {
        values.splice(idx, 1);
        if (values.length) {
          this.userData.save(this.exam, key, values.join(','));
        } else {
          this.userData.remove(this.exam, key);
          this.decrementStat(obj);
        }
      }
    }
  }
}

3. 工廠註冊與調用


const handlerMap = {
  'PD': new ChoiceHandler(exam, UserData, stats),
  'DANX': new ChoiceHandler(exam, UserData, stats),
  'PP': new ChoiceHandler(exam, UserData, stats),
  'text': new TextHandler(exam, UserData, stats),
  'textarea': new TextHandler(exam, UserData, stats),
  'checkbox': new CheckboxHandler(exam, UserData, stats)
};

function processAnswer(obj, objNameType) {
  const handler = handlerMap[objNameType];
  if (handler) handler.handle(obj);
}

重構收益

  • 開閉原則:新增題型只需添加新 Handler,不修改核心邏輯
  • 單元測試:每個 Handler 可獨立測試
  • 復用性:共用邏輯提取到基類
  • 可讀性:業務語義清晰,避免巨大的 switch 塊

輕量級替代:對象映射表

若邏輯較簡單,可用對象映射替代類:


const handlers = {
  'PD': (obj) => handleChoice(obj, 'id'),
  'DANX': (obj) => handleChoice(obj, 'name'),
  'text': (obj) => handleText(obj, 'text_'),
  'checkbox': handleCheckbox
  // ...
};

handlers[objNameType]?.(obj);
copyright © 萬盛學電腦網 all rights reserved