Java中的通用接口

时间:2015-12-30 13:55:45

标签: java android

有可能有类似的东西吗?我试图强制任何扩展此类的类来实现扩展BaseHomeListView

的接口
public abstract class BaseHomeFragment<T extends BaseHomeListView> extends BaseRecyclerViewFragment implements T 

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

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

2 个答案:

答案 0 :(得分:2)

您唯一明智的做法是:

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

然后,如果你有像

这样的东西
public interface FancyHomeListView extends BaseHomeListView<Fancy> {
}

然后你就可以得到像

这样的片段
public class FancyHomeFragment 
    extends BaseHomeFragment<Fancy>
    implements FancyHomeListView {
    //...
}

答案 1 :(得分:0)

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

    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;
}