HarmonyOS 应用开发《掌上英语》第27篇:学习统计持久化——StatisticsManager 的数据聚合方案
学习统计持久化——StatisticsManager 的数据聚合方案引言学习数据统计是教育类 App 的核心功能之一。用户完成一次练习后系统需要快速计算出正确率、各题型得分率、平均答题时长等指标并将这些数据持久化以便用户在学习报告等页面查看历史趋势。本文将以StatisticsManager的实现为例分析如何设计一套可扩展、可聚合的学习统计方案。一、数据模型设计统计数据的核心是PracticeStatistics接口它包含了全局统计和分题型统计两个维度exportinterfacePracticeStatistics{// 全局统计数据totalQuestions:number// 总答题数correctQuestions:number// 正确题数wrongQuestions:number// 错误题数correctRate:number// 正确率百分比vocabularyMasteryRate:number// 词汇掌握率listeningCorrectRate:number// 听力正确率readingCorrectRate:number// 阅读正确率clozeCorrectRate:number// 完形填空正确率avgAnswerTime:number// 平均答题时长秒// 分题型统计typeStatistics:TypeStat[]}exportinterfaceTypeStat{type:string// 题型编号1词汇 2听力 3阅读 4完形 5语法 6口语total:number// 该题型总题数correct:number// 正确数wrong:number// 错误数}设计亮点typeStatistics数组而非固定字段。这样可以支持未来新增题型而无需修改数据模型——符合开闭原则。二、单次练习统计计算calculateStatistics方法接收一次练习的题目列表和总时长实时计算各项指标publiccalculateStatistics(ques:TopicItemType[],duration:number):PracticeStatistics{try{lettotalQuestionsques.length;letcorrectQuestions0;letwrongQuestions0;lettypeStats:TypeStat[][];ques.forEach(item{if(item.isAnswer){// 判断答案是否正确letisCorrectthis.checkAnswerCorrect(item.selectQues,item.rightQues);if(isCorrect){correctQuestions;}else{wrongQuestions;}// 按题型累加统计lettypeKeyitem.type||其他;letfoundfalse;for(leti0;itypeStats.length;i){if(typeStats[i].typetypeKey){typeStats[i].total;if(isCorrect)typeStats[i].correct;elsetypeStats[i].wrong;foundtrue;break;}}if(!found){typeStats.push({type:typeKey,total:1,correct:isCorrect?1:0,wrong:isCorrect?0:1});}}});letcorrectRatetotalQuestions0?(correctQuestions/totalQuestions*100):0;// 各题型专项正确率letlisteningCorrectRatethis.getTypeCorrectRate(typeStats,2);letreadingCorrectRatethis.getTypeCorrectRate(typeStats,3);letclozeCorrectRatethis.getTypeCorrectRate(typeStats,4);letvocabularyMasteryRatethis.getTypeCorrectRate(typeStats,1);letavgAnswerTimetotalQuestions0?Math.floor(duration/totalQuestions):0;letstatistics:PracticeStatistics{totalQuestions,correctQuestions,wrongQuestions,correctRate:Math.round(correctRate*100)/100,vocabularyMasteryRate:Math.round(vocabularyMasteryRate*100)/100,listeningCorrectRate:Math.round(listeningCorrectRate*100)/100,readingCorrectRate:Math.round(readingCorrectRate*100)/100,clozeCorrectRate:Math.round(clozeCorrectRate*100)/100,avgAnswerTime,typeStatistics:typeStats};// 合并到历史数据this.saveStatistics(statistics);returnstatistics;}catch(e){Logger.error(StatisticsManager,计算统计数据失败:${JSON.stringify(e)});returnthis.getEmptyStatistics();}}核心逻辑遍历题目逐题判断是否正确同时按题型分类统计。答案比较checkAnswerCorrect比较selectQues和rightQues两个数组排序后是否完全一致。四舍五入使用Math.round(x * 100) / 100保留两位小数。降级处理异常时返回空统计数据不影响用户使用。三、历史数据聚合单次练习的数据需要与历史数据合并才能反映用户的长期学习趋势privatesaveStatistics(statistics:PracticeStatistics):void{try{lethistoryStatsthis.getHistoryStatistics();letmergedStats:PracticeStatistics{totalQuestions:historyStats.totalQuestionsstatistics.totalQuestions,correctQuestions:historyStats.correctQuestionsstatistics.correctQuestions,wrongQuestions:historyStats.wrongQuestionsstatistics.wrongQuestions,correctRate:statistics.totalQuestions0?statistics.correctRate:historyStats.correctRate,vocabularyMasteryRate:statistics.vocabularyMasteryRate,listeningCorrectRate:statistics.listeningCorrectRate,readingCorrectRate:statistics.readingCorrectRate,clozeCorrectRate:statistics.clozeCorrectRate,avgAnswerTime:statistics.avgAnswerTime,typeStatistics:this.mergeTypeStatistics(historyStats.typeStatistics,statistics.typeStatistics)};PreferenceUtil.getInstance().put(this.STATISTICS_KEY,mergedStats);}catch(e){Logger.error(StatisticsManager,保存统计数据失败:${JSON.stringify(e)});}}聚合策略累加型字段totalQuestions、correctQuestions、wrongQuestions历史值 新值直接相加。覆盖型字段correctRate、各专项正确率以最新一次计算为准。分题型统计通过mergeTypeStatistics方法进行深度合并。privatemergeTypeStatistics(history:TypeStat[],current:TypeStat[]):TypeStat[]{// 先深度复制历史数据letresult:TypeStat[][];for(leti0;ihistory.length;i){result.push({type:history[i].type,total:history[i].total,correct:history[i].correct,wrong:history[i].wrong});}// 合并当前数据for(leti0;icurrent.length;i){letfoundfalse;for(letj0;jresult.length;j){if(result[j].typecurrent[i].type){result[j].totalcurrent[i].total;result[j].correctcurrent[i].correct;result[j].wrongcurrent[i].wrong;foundtrue;break;}}if(!found){result.push({type:current[i].type,total:current[i].total,correct:current[i].correct,wrong:current[i].wrong});}}returnresult;}这里手动深度复制而非直接赋值是因为TypeStat是引用类型直接复制会共享底层对象导致历史数据被意外修改。四、历史数据读取与展示publicgetHistoryStatistics():PracticeStatistics{try{letstatsPreferenceUtil.getInstance().get(this.STATISTICS_KEY,undefined)asPracticeStatistics;if(!stats){returnthis.getEmptyStatistics();}returnstats;}catch(e){Logger.error(StatisticsManager,获取历史统计数据失败:${JSON.stringify(e)});returnthis.getEmptyStatistics();}}publicgetQuestionTypeStats():QuestionTypeStat[]{try{letstatsthis.getHistoryStatistics();letresult:QuestionTypeStat[][];for(leti0;istats.typeStatistics.length;i){lettypeStatstats.typeStatistics[i];result.push({typeName:this.getTypeName(typeStat.type),total:typeStat.total,correct:typeStat.correct,wrong:typeStat.wrong,correctRate:typeStat.total0?Math.round(typeStat.correct/typeStat.total*10000)/100:0});}returnresult.sort((a,b)b.total-a.total);}catch(e){Logger.error(StatisticsManager,获取题型统计失败:${JSON.stringify(e)});return[];}}getQuestionTypeStats将内部的数字题型编号转换为可读的中文名称并按总题数降序排列方便 UI 层展示。五、最佳实践5.1 空值安全首次使用或数据被清空时getHistoryStatistics返回空统计数据而非null避免调用方做空值检查privategetEmptyStatistics():PracticeStatistics{return{totalQuestions:0,correctQuestions:0,wrongQuestions:0,correctRate:0,vocabularyMasteryRate:0,listeningCorrectRate:0,readingCorrectRate:0,clozeCorrectRate:0,avgAnswerTime:0,typeStatistics:[]};}5.2 精度控制所有百分比值使用Math.round(x * 100) / 100确保保留两位小数避免浮点数精度问题导致 UI 上显示一长串小数。5.3 题型映射集中管理题型编号到中文名称的映射集中在getTypeName方法中避免在 UI 层散落 switch-caseprivategetTypeName(type:string):string{switch(type){case1:return单词拼写case2:return听力理解case3:return阅读理解case4:return完形填空case5:return语法练习case6:return口语练习default:return题型${type}}}六、总结StatisticsManager展现了一个典型的数据聚合场景从原始数据题目列表到计算指标正确率再到历史数据合并累加 覆盖最后到 UI 友好的展示格式题型名称转换 排序。这种分层设计使得统计逻辑高度内聚、易于测试同时在需要新增题型或统计维度时只需扩展TypeStat数组即可无需修改核心聚合逻辑。

相关新闻

Grok智能体后台模式详解:AI自动化任务的长时运行实践

Grok智能体后台模式详解:AI自动化任务的长时运行实践

今天来看一个值得关注的技术更新:Grok智能体现在支持后台模式运行。这个功能对于需要长时间运行AI任务的用户来说是个重要改进,意味着你可以让智能体在后台持续处理任务,而不需要保持终端窗口打开。Grok智能体是由xAI开发的AI执行系统&#x…

2026/11/21 15:45:11 阅读更多 →
第五章WSaiOS 多模态融合感知引擎实现

第五章WSaiOS 多模态融合感知引擎实现

第五章WSaiOS 多模态融合感知引擎实现WSaiOS Multimodal Fusion Perception Engine——构建统一世界感知数据入口5.1 多模态融合感知工程目标WSaiOS 多模态融合感知引擎的目标:将不同来源的数据:图像;视频;文本;音频&a…

2026/11/21 15:45:32 阅读更多 →
大模型时代程序员转型指南:从传统开发到AI工程化

大模型时代程序员转型指南:从传统开发到AI工程化

1. 大模型技术如何重塑程序员就业市场去年面试Java开发岗时,面试官突然问我是否了解LangChain框架,这个细节让我意识到技术风向正在发生根本性转变。现在打开任何招聘平台,算法工程师岗位JD中"熟悉大模型原理"几乎成为标配&#xf…

2026/11/19 4:09:29 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/20 23:27:28 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/20 23:27:28 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/20 23:27:28 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/20 21:55:32 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/20 23:27:28 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/20 22:59:12 阅读更多 →

日新闻

周新闻

月新闻