有一个不可变类:
Scope<Cmp extends Comparable<Cmp>>
public Scope<Cmp> crop(Scope<Cmp> scope) {
...
return new Scope<Cmp>(starts, ends);
}
它有许多类似的方法,由以下方法扩展:
Timerange extends Scope<Date>
和许多其他(也是不可变的)。
我希望他们返回其类型的对象。例如:
timerange.crop(scope)
应该返回 Timerange 对象,而不是 Scope。
我是否必须重写每个方法(或使用反射)? 还有其他方法吗?
提前致谢, 艾特姆。
最佳答案
你需要某种工厂。在这种情况下,工厂方法工作正常。
public abstract class Scope<E extends Comparable<E>> {
abstract Scope<E> create(E start, E end);
public Scope<E> crop(Scope<E> scope) {
...
return create(starts, ends);
}
}
public TimeRange extends Scope<Date> {
Scope<Date> create(Date start, Date end) {
return new TimeRange (...);
}
}
您可能希望向基类添加一个通用的“this”参数:
public abstract class Scope<THIS extends Scope<THIS, E>, E extend Comparable<E>> {
abstract THIS create(E start, E end);
public THIS crop(Scope<E> scope) {
...
return create(starts, ends);
}
}
public TimeRange extends Scope<TimeRange,Date> {
TimeRange create(Date start, Date end) {
return new TimeRange (...);
}
}
这确实给客户端代码增加了额外的工作。
关于java - 通用返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/848953/