我有如下的類。支持返回不同類型的方法的設計類/接口
public interface ITest <T>
{
public Set<T> methodHere();
}
public class test1 implements ITest<String>
{
Set<String> methodHere(){
return // Set of String
}
}
public class test2 implements ITest<Integer>
{
Set<Integer> methodHere(){
return // Set of Integer
}
}
public class ITestFactory {
public static ITest getInstance(int type) {
if(type == 1) return new test1();
else if(type == 2) return new test2();
}
}
public class TestUser {
public doSomething(int type) {
ITest t = ITestFactory.getInstance(type);
if(type == 1) Set<Integer> i = t.methodHere();
else if(type == 2) Set<String> s = t.methodHere();
...
}
}
工廠類有一個警告,ITest被用作原始類型。我應該做些什麼修改才能擺脫它?
TestUser代碼看起來很醜。我錯過了非常基本的東西嗎?我不想用Set<?>
感謝 Nayn
雖然這是一個很好的答案,但@Thirler的評論「當您調用getInstance時,不可能知道哪種類型將返回」,這讓我重新思考我的設計。我不使用泛型,但創建了一個乾淨的類層次結構。 – Nayn 2010-06-01 13:07:23
更新了我的問題。我仍然不正確。 – Nayn 2010-06-02 00:07:25