用java实现:文件StudentDB.java:单列类,模拟数据库中的课程,初始化后至少封装5名学生信息;
时间: 2024-03-15 19:44:56 浏览: 93
好的,以下是用 Java 实现的 StudentDB 单例类,模拟数据库中的课程,初始化后封装了5名学生的信息:
```java
import java.util.ArrayList;
import java.util.List;
public class StudentDB {
private static StudentDB instance = null;
private List<Student> students;
private StudentDB() {
students = new ArrayList<>();
students.add(new Student("John", "Doe", 1));
students.add(new Student("Jane", "Doe", 2));
students.add(new Student("Bob", "Smith", 3));
students.add(new Student("Alice", "Johnson", 4));
students.add(new Student("Tom", "Lee", 5));
}
public static synchronized StudentDB getInstance() {
if (instance == null) {
instance = new StudentDB();
}
return instance;
}
public List<Student> getStudents() {
return students;
}
}
class Student {
private String firstName;
private String lastName;
private int id;
public Student(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
```
这个类实现了单例模式,保证整个应用程序中只有一个 StudentDB 实例。在构造函数中初始化了5个学生,每个学生有名、姓和 ID 三个属性。可以通过 `getInstance()` 方法获取 StudentDB 实例,然后通过 `getStudents()` 方法获取学生列表。
阅读全文