如果有语法问题,请原谅。这样做的目的不是让代码变得完美,而是让设计变得完美。
我有一个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
这两者都会使用的接口(interface),并且具有 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 不应该实现相同的接口(interface)吗?
最佳答案
这个界面有一些问题:
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。
关于java - 定制表的通用设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160384/