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.
1111/StudentRepository.java

97 lines
2.4 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.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<String, Student> 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<Student> 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;
}
}