【发布时间】:2011-05-09 03:47:45
【问题描述】:
我正在尝试生成一些类来控制模型-视图-演示器应用程序。我提出了以下定义,但我正在努力避免递归泛型。
public abstract class Presenter<V extends View<...?>> {
protected V view;
public Presenter(V view) {
this.view = view;
}
// ...
}
public abstract class View<P extends Presenter<...?>> {
protected P presenter;
// ...
}
我想在两个类之间建立一种相互关系。我的想法是我可以为特定 View 实例化一个 Presenter,这两个类都依赖于抽象基类中定义的有用方法,但都知道正在使用对应抽象类的哪个子类。
我的问题是定义代码的..? 部分。我看不到避免递归情况的方法,例如:
public abstract class View<P extends Presenter<V>, V extends View<Q>, Q extends...>
甚至这个定义也不一致,因为 View 类现在需要两个通用参数……混乱。
我基本上是想避免类被对抽象类类型的引用弄得乱七八糟,这就需要在整个具体实现中进行大量转换,如下所示:
// simpler option
public abstract class Presenter {
protected View view;
public Presenter(View view) {
this.view = view;
}
}
public class FooPresenter extends Presenter {
public FooPresenter(BarView view) {
super(view);
}
public someMethod() {
((BarView) getView()).viewSpecificMethod();
}
}
这些类的每个具体实现都需要不断地从抽象类型转换为它“知道”正在使用的类型。
【问题讨论】: