有一个不变的类:
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 - 一般 yield ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/848953/