繁体   English   中英

Java中的通用接口

[英]Generic interface in Java

有可能有类似的东西吗? 我正在尝试强制任何扩展此类的类来实现扩展BaseHomeListView的接口

public abstract class BaseHomeFragment<T extends BaseHomeListView> extends BaseRecyclerViewFragment implements T 

我正在尝试在Android中为一些仅显示列表的片段实现MVP模式。 所以基本上视图必须是rendersList,这就是它在基本接口中的原因,但我仍然希望允许每个片段在需要时添加更多方法

public interface BaseHomeListView<T> extends LoadDataView, LoadMoreView<T> {
   void renderList(Collection<T> items);
}

你唯一明智的做法是:

public abstract class BaseHomeFragment<T> 
    extends BaseRecyclerViewFragment 
    implements BaseHomeListView<T>

然后,如果你有类似的东西

public interface FancyHomeListView extends BaseHomeListView<Fancy> {
}

然后你就可以得到像这样的片段

public class FancyHomeFragment 
    extends BaseHomeFragment<Fancy>
    implements FancyHomeListView {
    //...
}

假设您想要在每个子类中更改接口方法的实现,而不是更改此类方法的参数,或者解耦片段视图的业务代码,那么将此类接口的通用实例添加为成员的更为合理你的片段类。

    public abstract class BaseHomeFragment<T extends BaseHomeListView> extends BaseRecyclerViewFragment {

/*the class information can be used against a factory method to get an instance of the interface*/
private Class<T> myInterfaceClass;
protected T myInterfaceInstance;

public void setMyInterFaceInstance(T instance){
myInterfaceInstance = instance;
}

public BaseHomeFragment(Class<T> initializeClass){
myInterfaceClass = initializeClass;
myInterfaceInstance = interfaceFactory(myInterfaceClass);

}

//TODO: use the interface instance.

}

现在,在每个子类中,您需要将接口子类作为参数添加到super:

public class myAppHomeFragment extends BaseHomeFragment<AppHomeListView>{

public myAppHomeFragment(){
super(AppHomeListView.class);
setMyInterFaceInstance(new AppHomeListView{
//Method overloading
});

}
//TODO: Use the interface's new methods if necessary.

}

您的工厂方法的一个小例子:

public static <T extends BaseHomeListView> T interfaceFactory(Class<T> aClass){

if(aClass.getSimpleName().equals("someclass")){
//TODO
return new someclass;
}
return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM