java - 定制表的通用设计

标签 java generics design-patterns

如果有语法问题,请原谅。这样做的目的不是让代码变得完美,而是让设计变得完美。

我有一个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>但这又遇到了同样的问题。

我还想也许我可以制作 TableOneTableTwo类使用相同的泛型,即 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/

相关文章:

java - 在哪里可以找到 JSR-275 替代品?

java - PropertyValueFactory 是否需要模型中的 valueProperty 方法?

java - 使用有界泛型编译 lambda 时出错

c# - C# 泛型是否支持类型签名约束?

c# - c#除了enum还能用什么

java - 使用 IKVM 和 ikvmc hibernate

java - 谁能告诉我 java 中 volatile 和 static 的区别

java - 如何扩展列表中包含的对象?

java - 在开始 Android 开发之前我应该​​学习哪些设计模式

java - 枚举设计决策的常量特定方法