我有以下界面:
public interface ClusterPopulation
{
public double computeDistance(ClusterPopulation other);
}
Run Code Online (Sandbox Code Playgroud)
是否可以在接口本身中指定,ClusterPopulation的实现A只能将A实现作为computeDistance的参数?
我看到的唯一的approching解决方案如下,但我不喜欢它:
使用泛型重新定义界面:
public interface ClusterPopulation
{
public <T extends ClusterPopulation> double computeDistance(T other);
}
Run Code Online (Sandbox Code Playgroud)
在实现中,如果参数不是来自良好类型,则抛出IllegalArgumentException,如果类型正常,则执行一些强制转换... Meeeeh!
即使采用这种方法,最终用户也只是通过阅读文档/查看代码实现/试验和错误来了解约束...
更好的解决方案?
您使用泛型有正确的想法,但不是将其应用于方法,而是将其应用于整个界面.
public interface ClusterPopulation<T extends ClusterPopulation<T>>
{
double computeDistance(T other);
}
Run Code Online (Sandbox Code Playgroud)
这允许实现定义T为自身.
public class ClusterPopulationA implements ClusterPopulation<ClusterPopulationA> { // ...
Run Code Online (Sandbox Code Playgroud)
但是,它不允许实现将其定义为其他内容.
public class BreaksPattern implements ClusterPopulation<ClusterPopulationA>
Run Code Online (Sandbox Code Playgroud)
在您的文档中包含所有子类应将type参数定义T为其自己的类.
| 归档时间: |
|
| 查看次数: |
40 次 |
| 最近记录: |