本项目主要目的是练习如何管理学生对象和课程对象。在之前的项目中,我们创建了与学生相关的五个类,它们是Student类、Freshman类、Sophomore类、Junior类和Senior类。在本项目中我们首先需要在com.littlewaterdrop.bean包中创建一个新类Course,用于表示课程。
Course类是一个公有类,它有三个私有成员变量,分别是:(1) id,字符串类型,用于表示唯一的课程号;(2) name,字符串类型,用于表示课程名称;(3) credit,单精度浮点数类型,用于表示课程的学分。
Course类有一个公有构造函数,它接受三个参数:(1) id,字符串类型;(2) name,字符串类型和(3) credit,单精度浮点数类型,分别用于初始化三个私有成员变量。
Course类还为每个成员变量提供了getter和setter方法(其实现要求与Student类相同)。
public class Course {
// private String id = null;
// private String name = null;
// private Float credit = null;
// ...
}
然后,在包com.littlewaterdrop.factory中创建一个新类CourseFactory。该类是公有类(public)。该类声明了一个公有静态方法newCourse()。该方法用于创建Course类对象。该方法接受三个参数,分别为id、name和credit,用于初始化新生成的Course对象中的成员变量。这种创建对象的方法被称为工厂模式。
public class CourseFactory {
public static Course newCourse(String id, String name, Float credit) {
// ...
}
}
本项目要求在com.littlewaterdrop.registration包中创建一个新类StudentCenter,用于表示学生中心。学生中心主要用于保存所有学生信息、所有课程信息、和所有学生注册课程的信息。本项目要求使用单例模式来实现StudentCenter类。即在整个应用程序中,只能创建出一个StudentCenter对象。
因此,StudentCenter类的构造函数是私有的。StudentCenter类还声明了一个公有静态方法getInstance(),用于获得唯一的StudentCenter对象。getInstance()方法的原型如下。
public static StudentCenter getInstance();
StudentCenter还提供了两个公有成员方法。getAllStudents()方法返回所有在册学生对象;getAllCourses()方法返回所有在册课程对象。这两个方法的原型如下。
public Student[] getAllStudents();
public Course[] getAllCourses();
在本项目中,为了简化处理,在上述两个方法中,可以直接返回如下学生列表和课程列表。
Student[] allStudents = {
StudentFactory.newFreshman("0001", "James", "Computer Science"),
StudentFactory.newSophomore("0002", "Amy", "Biology"),
StudentFactory.newJunior("0003", "David", "Mathematics"),
StudentFactory.newSenior("0004", "Cindy", "Chemistry"),
};
Course[] allCourses = {
CourseFactory.newCourse("CS0201", "Java Programming", 3.5f)
};