diff --git a/StudentRepository.java b/StudentRepository.java new file mode 100644 index 0000000..8fd2921 --- /dev/null +++ b/StudentRepository.java @@ -0,0 +1,97 @@ +package com.student.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 学生数据仓库类,负责学生数据的存储、检索、更新和删除 + * 使用单例模式确保系统中只有一个数据仓库实例 + */ +public class StudentRepository { + // 使用Map存储学生数据,以ID为键 + private final Map students; + // 单例实例 + private static volatile StudentRepository instance; + + /** + * 私有构造函数,防止外部实例化 + */ + private StudentRepository() { + students = new HashMap<>(); + // 初始化一些示例数据 + addSampleData(); + } + + /** + * 获取单例实例 + * @return StudentRepository实例 + */ + public static StudentRepository getInstance() { + if (instance == null) { + synchronized (StudentRepository.class) { + if (instance == null) { + instance = new StudentRepository(); + } + } + } + return instance; + } + + /** + * 添加示例数据 + */ + private void addSampleData() { + addStudent(new Student("1", "张三", 20, "计算机科学")); + addStudent(new Student("2", "李四", 21, "软件工程")); + addStudent(new Student("3", "王五", 19, "数据结构")); + } + + /** + * 添加学生 + * @param student 学生对象 + */ + public void addStudent(Student student) { + students.put(student.getId(), student); + } + + /** + * 根据ID获取学生 + * @param id 学生ID + * @return 学生对象,如果不存在则返回null + */ + public Student getStudentById(String id) { + return students.get(id); + } + + /** + * 获取所有学生 + * @return 学生列表 + */ + public List getAllStudents() { + return new ArrayList<>(students.values()); + } + + /** + * 更新学生信息 + * @param student 更新后的学生对象 + * @return 是否更新成功 + */ + public boolean updateStudent(Student student) { + if (students.containsKey(student.getId())) { + students.put(student.getId(), student); + return true; + } + return false; + } + + /** + * 删除学生 + * @param id 学生ID + * @return 是否删除成功 + */ + public boolean deleteStudent(String id) { + return students.remove(id) != null; + } +} \ No newline at end of file