成員的未經檢查的呼叫我有一個服務,我在做很多if/else語句,所以我發現使用策略模式可以幫助我很多。Java策略模式 - 作爲
我正在與Mongo合作,我需要在數據庫中存儲兩個不同的模型在不同的集合中。這些模型擴展了一些具有一些類似信息的通用模型我開始在運行時決定使用什麼類,但現在我的代碼顯示警告:unchecked call to 'save(T)' as a member of type 'Strategy'
。
下面是我正在嘗試的代碼。目前,我剛剛添加了一個@SuppressWarnings("unchecked")
,目前工作正常,但我想確認這是否會導致問題,以及哪種方法更好。
問題:我該如何解決這個問題?
守則截至目前:
interface Strategy<T extends Person> {
T save(T model);
//other methods
}
class StudentStrategy implements Strategy<Student> {
private StudentRepository studentRepository;
public Student save(Student student) {
return studentRepository.save(student);
}
}
class TeacherStrategy implements Strategy<Teacher> {
private TeacherRepository teacherRepository;
public Teacher save(Teacher teacher) {
return teacherRepository.save(teacher);
}
}
class PersonService {
void doSomething(Person person) {
Strategy strategy = StrategyFactory.getStrategy(person.getType());
strategy.save(person); //THIS LINE SAYS A unchecked call to 'save(T)' as a member of type 'Strategy'
}
}
class StrategyFactory {
public static Strategy getStrategy(PersonType personType) {
if(personType == STUDENT) return new StudentStrategy();
if(personType == TEACHER) return new TeacherStrategy();
return null;
}
}
舊代碼:
這是我以前做的代碼。正如你所看到的,有很多if/else。更改庫存儲的人不是一個選項,因爲我需要每個子類的信息..
class OldPersonService {
void doSomething(Person person) {
if(person.getType == STUDENT) {
studentRepository.save(person);
} else {
teacherRepository.save(person);
}
person.setBirthday(new Date());
person.setName("john");
if(person.getType == STUDENT) {
studentRepository.findReferals(person);
} else {
teacherRepository.findReferals(person);
}
}
}
見例如https://stackoverflow.com/q/2770321/2891664和https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html。但是,提出解決方案有點困難,但不知道你在做什麼。實際上,這裏比較傳統的解決方案根本不使用泛型或策略,而是在'Student'和'Teacher'覆蓋的'Person'類中編寫抽象方法。另一種可能性可能像我在這裏的答案中所示:https://stackoverflow.com/a/44422954/2891664。 – Radiodef
hi @Radiodef!我嘗試過使用抽象,問題是,如果我這樣做,我的存儲庫將無法返回每個子類,我將無法訪問它的每個單獨的屬性。但感謝鏈接,它有助於更多地瞭解泛型! :) –
可能重複[什麼是原始類型,爲什麼我們不應該使用它?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt -we-use-it) – Tom