如果有语法问题,请原谅。这样做的目的不是为了得到完美的代码,而是为了得到设计。
我有一台interface ITable<T>
public interface ITable<T> {
public Collection<T> getEntries();
public void add(CustomObj value);
public Collection<CustomObj> getCustomObjects();
}它由两个类使用:
TableOne<CustomObj>和TableTwo<Pair<CustomObj, CustomObj>>
然后我有一个接口,它使用一个函数来应用这些表
public interface ITableFunction<T> {
public abstract Collection<ITable<?>> execute(Collection<ITable<T>> tables);
}当我试图创建一个泛型抽象类时,我的两难境地就出现了
public abstract class AbstractTableFunctionCombined<T> implements ITableFunction<T>{
private boolean someBool;
public AbstractTableFunctionCombined(boolean someBool){
this.someBool = someBool;
}
@Override
public Collection<ITable<?>> execute(Collection<ITable<T>> tables){
// What i would like to do, but can't right now:
ITable<T> combinedTable;
if (someBool){
combinedTable = new TableOne();
} else {
combinedTable = new TableTwo();
}
for(ITable<T> table : tables){
combinedTable.addAll(table.getCustomObjects());
}
for(T entry : table.getEntries()){
execute(entry);
}
}
public abstract void execute(T entry);
}问题是我不能保证T类型与我试图实例化的表相同。我想我必须从Pair<CustomObj, CustomObj>和常规的CustomObj中创建某种关系。我尝试创建一个这两个都会使用的Entry接口,并将ITable<T>设置为ITable<T extends Entry>,但同样遇到了同样的问题。
我还想,也许我可以让TableOne和TableTwo类使用相同的泛型,即TableTwo<T> implements ITable<T>,但TableTwo对使用Pair<CustomObj, CustomObj>有严格的限制。
我是否必须创建两个独立的类:AbstractTableFunctionOne<CustomObj>和AbstractTableFunctionTwo<Pair<CustomObj, CustomObj>>?我想避免这一点,因为这将是许多重复的代码。
或者我是不是太强迫这种面向对象的设计了?TableOne和TableTwo甚至不应该实现相同的接口吗?
发布于 2015-12-09 00:06:19
此接口有一些问题:
public interface ITableFunction {
public abstract execute(Collection<ITable<T>> tables);
}您需要一个返回类型和一个泛型:
public interface ITableFunction<T> {
public abstract void execute(Collection<ITable<T>> tables);
}和方法的返回类型
public Collection<ITable<T>> execute(Collection<ITable<T>> tables){
..在声明和实现中应为Collection或void。
https://stackoverflow.com/questions/34160384
复制相似问题