鸿蒙掌上驾考宝典应用开发21:ExamService 数据服务——单例模式与数据管理
·
第21篇:ExamService 数据服务——单例模式与数据管理

一、引言
ExamService 是整个驾考应用的数据核心,负责试题管理、答题统计、成绩计算等核心功能。它采用单例模式确保全局数据一致性,并通过 @ObservedV2 / @Trace 实现响应式数据绑定。本文将深入解析 ExamService 的设计与实现。
二、单例模式
2.1 实现
@ObservedV2
export class ExamService {
private static _instance: ExamService;
private examDetails: ExamDetail[] = [];
@Trace mockExamCount: number = 0;
@Trace mockExamScore: number[] = [];
static context: Context;
private constructor() {
this.examDetails = this.generateExamDetail();
}
public static instance(context: Context) {
ExamService.context = context;
if (!ExamService._instance) {
ExamService._instance = new ExamService();
}
return ExamService._instance;
}
}
2.2 使用场景
// 在组件中获取 ExamService 实例
const examService = ExamService.instance(this.getUIContext().getHostContext() as Context);
// 获取统计数据
const totalCount = examService.getTotalCount();
const didCount = examService.getDidCount();
const accuracyRate = examService.calAccuracyRate();
const averageScore = examService.calculateAverageScore();
三、核心数据统计
3.1 答题统计
// 总题数
public getTotalCount(): number {
return this.examDetails.length;
}
// 已做题数
public getDidCount(): number {
return this.examDetails.filter(item => item.isCorrect !== undefined).length;
}
// 正确数
public getCorrectCount(): number {
return this.examDetails.filter(item => item.isCorrect === true).length;
}
// 错题数
public getErrorCount(): number {
return this.examDetails.filter(item => item.isCorrect === false).length;
}
// 收藏数
public getCollectCount(): number {
return this.examDetails.filter(item => item.isCollect === true).length;
}
3.2 正确率与平均分
// 正确率
public calAccuracyRate(): number {
const rightCount = this.getCorrectCount();
const totalCount = this.getTotalCount();
if (rightCount === 0) return 0;
return Math.ceil(rightCount / totalCount * 100);
}
// 平均分
public calculateAverageScore(): number {
if (this.mockExamCount === 0) return 0;
return Math.ceil(this.mockExamScore.reduce((pre, next) => pre + next) / this.mockExamCount);
}
四、试卷管理
4.1 试卷缓存
// 需要缓存的场景
const NEED_NEW_LIST = [EXAM_MANAGER_TYPE.random, EXAM_MANAGER_TYPE.error, EXAM_MANAGER_TYPE.collect];
getManagerByName(name: string | Resource, type: EXAM_MANAGER_TYPE, ...): ExamManager {
let examManager = this.examManagerList.find(item => item.name === name);
if (examManager === undefined || wrongOrCollect !== undefined) {
const examList = this.getExamQuestionList(type, chapterName, name as string, wrongOrCollect);
examManager = new ExamManager(name, examList, ...);
// 需要缓存的场景才缓存
NEED_NEW_LIST.indexOf(type) === -1 && this.examManagerList.push(examManager);
}
return examManager;
}
五、总结
ExamService 通过单例模式实现了全局数据统一管理,结合 @ObservedV2 / @Trace 实现了响应式数据绑定,为 UI 组件提供实时的数据更新。
关键源码文件:
commons/datasource/src/main/ets/ExamService.ets
更多推荐





所有评论(0)