首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自定义表格的通用设计

自定义表格的通用设计
EN

Stack Overflow用户
提问于 2015-12-08 23:59:24
回答 1查看 43关注 0票数 1

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

我有一台interface ITable<T>

代码语言:javascript
复制
public interface ITable<T> {
    public Collection<T> getEntries();
    public void add(CustomObj value);
    public Collection<CustomObj> getCustomObjects();
}

它由两个类使用:

TableOne<CustomObj>TableTwo<Pair<CustomObj, CustomObj>>

然后我有一个接口,它使用一个函数来应用这些表

代码语言:javascript
复制
public interface ITableFunction<T> {
    public abstract Collection<ITable<?>> execute(Collection<ITable<T>> tables);
}

当我试图创建一个泛型抽象类时,我的两难境地就出现了

代码语言:javascript
复制
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>,但同样遇到了同样的问题。

我还想,也许我可以让TableOneTableTwo类使用相同的泛型,即TableTwo<T> implements ITable<T>,但TableTwo对使用Pair<CustomObj, CustomObj>有严格的限制。

我是否必须创建两个独立的类:AbstractTableFunctionOne<CustomObj>AbstractTableFunctionTwo<Pair<CustomObj, CustomObj>>?我想避免这一点,因为这将是许多重复的代码。

或者我是不是太强迫这种面向对象的设计了?TableOne和TableTwo甚至不应该实现相同的接口吗?

EN

回答 1

Stack Overflow用户

发布于 2015-12-09 00:06:19

此接口有一些问题:

代码语言:javascript
复制
public interface ITableFunction {
    public abstract execute(Collection<ITable<T>> tables);
}

您需要一个返回类型和一个泛型:

代码语言:javascript
复制
public interface ITableFunction<T> {
    public abstract void execute(Collection<ITable<T>> tables);
}

和方法的返回类型

代码语言:javascript
复制
public Collection<ITable<T>> execute(Collection<ITable<T>> tables){
..

在声明和实现中应为Collection或void。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34160384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档