2017-07-06 3 views
0
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); 
} 
... 
} 

一般化するために、私は '条件'を使用することができ、学生のインスタンスがBTechStudentかMasterStudentかどうかをチェックし、適切なBTechStudentまたはMasterStudentオブジェクトを返すことができます。オブジェクトを提供するためのファクトリパターンで一般化されたメソッドを書くには?

これらの2つの方法を一般化するための方が良い方法はありますか?

注: - BTechStudentクラスとMasterStudentクラスは、Studentクラスを拡張します。

ありがとうございました。

答えて

1

私はそれを正しく理解している場合わからないんだけど、これはあなたが助けかどうかを確認:

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); 
関連する問題