-
将Main类的createStudent() 方法提取出来,创建一个工厂类
-
工厂方法一般都是静态方法,只需通过类名即可访问对应的工厂方法
public class StudentFactory {
public static Student createStudent(String studentType) {
if ("小学生".equals(studentType)) {
return new Pupil();
} else if ("初中生".equals(studentType)) {
return new MiddleSchoolStudent();
} else if ("高中生".equals(studentType)) {
return new HighSchoolStudent();
}
System.out.println("尚不支持\"" + studentType + "\"这种学生类型");
return null;
}
}
-
在Main类的main方法中,通过工厂创建对应的学生实例
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String studentType = scanner.next();
Student student = StudentFactory.createStudent(studentType);
if (student != null) {
student.study();
}
}
}