2013-06-24 84 views
1

我有關於接口設計的問題。我將嘗試用下面的一個簡單例子來說明。沒有指定類型的Java接口

可以想象我有一個接口:

public interface TestInterface { 

    public List getData(); 

} 

,我有一個實現類:

public class TestInterfaceImpl implements TestInterface{ 

    public List<Customer> getData() { 
     return null; //will return a list of customers 
    } 
} 

我這個糟糕的設計在接口返回一個列表,而不指定(列表)類型和然後在實現類(List)中指定它?

謝謝 - 任何意見表示讚賞。

回答

9

在任何新代碼中使用raw types都是一個壞主意。相反,parameterize the interface.

public interface TestInterface<T> { 

    public List<T> getData(); 

} 

public class TestInterfaceImpl implements TestInterface<Customer> { 

    public List<Customer> getData() { 
     return null; //will return a list of customers 
    } 
} 

如果您以前從未編寫過一個通用類,或者只是不能確定所有的細節,你會發現the Java Tutorial's Generics Lesson有用。

3

您可能需要使用參數化IFACE:

public interface TestInterface<T> { 

    public List<T> getData(); 

} 

public class TestInterfaceImpl implements TestInterface<Customer> { 

    public List<Customer> getData() { 
     return null; //will return a list of customers 
    } 
} 
3

好吧,這不是壞的設計本身,而是泛型較好,類型安全設計:

//parametrize your interface with a general type T 
public interface TestInterface<T> { 
    public List<T> getData(); 
} 

//pass a real type to an interface 
public class TestInterfaceImpl implements TestInterface<Customer> { 
    public List<Customer> getData() { 
     return null; 
    } 
}