如何在工厂模式中编写泛化方法来提供对象?
How to write a generalized method in Factory Pattern to provide object?
public class GsonStudentFactory{
....
public static MasterStudent createMasterStudent(Student student) {
return gson.fromJson(student.getBody(), MasterStudent.class);
}
public static BTechStudent createBtechStudent(Student student) {
return gson.fromJson(student.getBody(), BTechStudent.class);
}
...
}
为了概括,我可以使用 'if' 条件,我可以检查 'if instance of student is BTechStudent or MasterStudent' 和 return 适当的 BTechStudent 或 MasterStudent 对象。
有没有更好的方法来概括这两种方法?
注意:- BTechStudent 和 MasterStudent classes extends Student class.
提前致谢。
我不确定我是否理解正确,但看看这是否对你有帮助:
public static <T extends Student> T createStudent(Student student) {
return gson.fromJson(student.getBody(), (Class<T>) student.getClass());
}
并像这样使用它:
MasterStudent masterStudent = createStudent(student);
或
BTechStudent btech = createStudent(student);
public class GsonStudentFactory{
....
public static MasterStudent createMasterStudent(Student student) {
return gson.fromJson(student.getBody(), MasterStudent.class);
}
public static BTechStudent createBtechStudent(Student student) {
return gson.fromJson(student.getBody(), BTechStudent.class);
}
...
}
为了概括,我可以使用 'if' 条件,我可以检查 'if instance of student is BTechStudent or MasterStudent' 和 return 适当的 BTechStudent 或 MasterStudent 对象。
有没有更好的方法来概括这两种方法?
注意:- BTechStudent 和 MasterStudent classes extends Student class.
提前致谢。
我不确定我是否理解正确,但看看这是否对你有帮助:
public static <T extends Student> T createStudent(Student student) {
return gson.fromJson(student.getBody(), (Class<T>) student.getClass());
}
并像这样使用它:
MasterStudent masterStudent = createStudent(student);
或
BTechStudent btech = createStudent(student);