2013-06-24 102 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; 
    } 
}