我正在尝试在 Android 中使用 MVP(模型- View -演示者)模式来实现我的应用程序,但我遇到了问题。我想要一个抽象的基本演示者,其 View 类属性为通用类型 ViewInterface
,但在创建真正的演示者时,我希望此属性的类型为 RealPresenterView
code> 如果可能的话,不需要覆盖所有演示者中的相同函数。
因为我可能没有正确解释自己,所以这里有一些代码来说明这种情况,首先是基本演示者:
abstract public class BasePresenter {
protected ViewInterface view;
protected ViewInterface getView() {
return view;
}
}
然后才是真正的主讲人
public class RealPresenter {
protected RealPresenterView view;
// ...
view.methodOnlyExistingInRealPresenterView();
}
我希望能够将 RealPresenter 中的 View 用作 RealPresenterView,而不需要在类中添加太多代码。这可能吗?
我已经阅读了有关类模板的内容,但我还没有看到如何在这种情况下实现而不在每个演示者中添加功能。
最佳答案
您可以使用泛型:
基本演示者
abstract public class BasePresenter<T extends ViewInterface> {
protected T view;
protected T getView() {
return view;
}
}
RealPresenter
public class RealPresenter extends BasePresenter<RealPresenterView> {
}
请注意,我有一段时间没有用 java 编写代码了,但我认为没关系。
关于java - 在java android中覆盖子类中的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43273398/