┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 菜單交互層 │ ←→ │ 業務邏輯層 │ ←→ │ 數據持久層 │
│ (Scanner) │ │ (Service) │ │ (File/DB) │
└─────────────┘ └─────────────┘ └─────────────┘
// 實體
class Student {
String id, name;
Map<String, Double> scores; // 科目→分數
// getters/setters, toString()
}
// DAO 接口
interface StudentDao {
void save(Student s);
Student findByName(String name);
Student findById(String id);
List<Student> findAll();
void update(Student s);
void delete(String id);
}
// 文件實現(CSV 格式)
class FileStudentDao implements StudentDao {
private final Path file = Paths.get("students.csv");
// 實現 CRUD,每行:id,name,math,english,physics...
}
// 業務服務
class StudentService {
private final StudentDao dao;
// 封裝排序、統計邏輯
List<Student> rankBySubject(String subject) { ... }
List<Student> rankById(String subject) { ... }
}
Files.readAllLines/Files.write + CSV 解析(推薦 OpenCSV 或手寫 split(","))。ObjectOutputStream 直接存對象圖,但版本升級不兼容,不推薦長期項目。while (true) {
System.out.println("""
1. 添加學生
2. 按姓名查詢
3. 科目成績排名
4. 學號成績排名
5. 退出
請選擇:""");
int cmd = scanner.nextInt();
switch (cmd) {
case 1 -> addStudent();
case 2 -> queryByName();
case 3 -> rankBySubject();
case 4 -> rankById();
case 5 -> System.exit(0);
}
}
ServiceLoader 實現 DAO 插件化(文件/H2/MySQL 熱插拔)。TablePrinter 美化控制台表格輸出。「先跑通文件版,再遷移到 H2」是最平滑的學習曲線。核心難點在排序邏輯與文件並發,建議早期引入
ReentrantReadWriteLock保護文件讀寫。