使用接口(interface)是提供抽象的好方法,如果可能的话我通常会尝试使用它。但这次我的情况有点不同,我不确定在这里使用是否是一个好的做法。
我有两个不同的类,需要一些具有相同签名的查询方法。比如说 MyString 和 MyInteger。
我正在考虑用一种方法定义一个接口(interface):
public interface MyInterface{
// no type is specified for the list, because each implementation will have different type of object
List query();
}
所以基本上我需要实现两个不同的类来实现上面的接口(interface)。第一个将得到 List<String>
,第二个将得到 List<Integer>
查询方法的结果。
问题是我不喜欢在接口(interface)中不指定泛型类型,因为稍后我需要进行强制转换。
那么在这里使用接口(interface)是否有意义,或者更好地实现两个具有相同方法签名而没有公共(public)接口(interface)的单独类?
最佳答案
The thing is I do not like not specifying generic type of in the interface...
这正是您解决此问题的方式。
When I need to get the object from list lets say Integer x = (Integer)list.get(index); This is just an example, indeed I use user defined object.
泛型的全部意义在于您不需要需要这样做。相反:
public interface MyInterface<T> {
List<T> query();
}
public class MyInteger implements MyInterface<Integer> {
// ...
}
// ...
MyInteger foo = new MyInteger();
// ...
List<Integer> list = foo.query();
// ...
Integer i = list.get(index);
或者使用 var
,因为它已经出现在该语言中一段时间了:
// ...
var foo = new MyInteger();
// ...
var list = foo.query();
// ...
var i = list.get(index);
So does it make sense to use interface here, or better to implement two separate class with same method signature without common interface ?
这要看情况。如果您有多个类将实现 MyInterface<Integer>
并且您需要以通用方式处理这些类的实例(例如,您使用 MyInterface<Integer>
而不是类来引用它们)和/或 if MyInterface
代表了整体结构的一些基本方面,那么使用接口(interface)可能是有意义的。如果你不这样做,如果只是你将有两个不同的类 List<something> query
方法,也可能不会。这取决于整体设计和(一点)风格。
关于java - 当存在不同的泛型类型时使用接口(interface)是否有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317916/