写一段使用java工厂模式来实现添加学生的功能。
时间: 2024-03-14 22:42:49 浏览: 19
好的,以下是使用Java工厂模式来实现添加学生的示例代码:
首先,我们定义一个抽象的学生类,包括学生的基本信息属性和方法:
```java
public abstract class Student {
protected String name;
protected int age;
protected String gender;
// ... 其他属性
public abstract void showInfo(); // 展示学生信息
}
```
然后,我们创建两个具体的学生类,分别为普通学生和优秀学生:
```java
public class OrdinaryStudent extends Student {
public OrdinaryStudent(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
// ... 其他属性初始化
}
@Override
public void showInfo() {
System.out.println("普通学生:" + name + ", " + age + "岁, " + gender);
}
}
public class ExcellentStudent extends Student {
public ExcellentStudent(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
// ... 其他属性初始化
}
@Override
public void showInfo() {
System.out.println("优秀学生:" + name + ", " + age + "岁, " + gender);
}
}
```
接着,我们创建一个学生工厂类,用于根据管理员输入的参数创建相应的学生对象:
```java
public class StudentFactory {
public static final int TYPE_ORDINARY = 1; // 普通学生
public static final int TYPE_EXCELLENT = 2; // 优秀学生
public static Student createStudent(int type, String name, int age, String gender) {
switch (type) {
case TYPE_ORDINARY:
return new OrdinaryStudent(name, age, gender);
case TYPE_EXCELLENT:
return new ExcellentStudent(name, age, gender);
default:
throw new IllegalArgumentException("无效的学生类型");
}
}
}
```
最后,在管理员选择添加学生时,调用学生工厂类的方法,根据管理员输入的参数创建相应的学生对象,并将其保存到数据库中:
```java
public class Admin {
public void addStudent(int type, String name, int age, String gender) {
Student student = StudentFactory.createStudent(type, name, age, gender);
// 将学生对象保存到数据库中
}
}
```
这样,我们就使用Java工厂模式来实现了添加学生的功能。