You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.mathgenerator.service;
import com.mathgenerator.model.User;
import com.mathgenerator.model.Level;
import com.mathgenerator.service.strategy.PaperStrategy; // 导入策略接口
import com.mathgenerator.storage.FileManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 它现在依赖一个PaperStrategy来决定题目组合方式。
*/
public class PaperService {
private final FileManager fileManager;
private final PaperStrategy paperStrategy; // 持有策略接口的引用
/**
* PaperService的构造函数。
* <p>
* 通过构造函数注入其依赖的文件管理器和试卷组合策略。
* 这种设计遵循了依赖注入DI原则增强了代码的模块化和可测试性。
*
* @param fileManager 用于处理文件读写的FileManager实例。
* @param paperStrategy 用于决定题目组合方式的PaperStrategy实例。
*/
public PaperService(FileManager fileManager, PaperStrategy paperStrategy) {
this.fileManager = fileManager;
this.paperStrategy = paperStrategy;
}
/**
* 创建并保存一份完整的试卷。
* <p>
* 这是该服务的核心方法。它 orchestrates 整个流程:
* 1. 加载指定用户的历史题目以进行查重。
* 2. 进入循环,委托给注入的 {@link PaperStrategy} 来动态选择题目生成器。
* 3. 生成新题目并进行查重,直到满足指定的题目数量。
* 4. 调用 {@link FileManager} 将最终的试卷内容保存到文件中。
*
* @param user 当前已登录的用户对象。
* @param count 需要生成的题目数量。
* @param currentLevel 用户当前选择的主难度级别。
*/
public void createAndSavePaper(User user, int count, Level currentLevel) {
Set<String> existingQuestions = fileManager.loadExistingQuestions(user.username());
List<String> newPaper = new ArrayList<>();
Set<String> generatedInSession = new HashSet<>();
System.out.println("正在根据策略生成题目,请稍候...");
while (newPaper.size() < count) {
// 将选择生成器的逻辑委托给策略对象
String question = paperStrategy.selectGenerator(currentLevel).generateSingleQuestion();
if (!existingQuestions.contains(question) && !generatedInSession.contains(question)) {
newPaper.add(question);
generatedInSession.add(question);
}
}
try {
String filePath = fileManager.savePaper(user.username(), newPaper);
System.out.println("成功!" + count + "道"+ currentLevel.getChineseName() + "数学题目已生成。");
System.out.println("文件已保存至: " + filePath);
} catch (IOException e) {
System.err.println("错误:保存文件失败 - " + e.getMessage());
}
}
}