处理集合的通用函数

时间:2015-08-01 10:44:09

标签: java

我有这样的功能

    private void writeResultsIntoSheets(WritableWorkbook workbook, List<JournalEntry> summaries) throws WriteException, RowsExceededException {
        String sheetName = "Journal Entry Summary";

        WritableSheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            int sheetIndex = 0;
            if (workbook.getNumberOfSheets() > 0) sheetIndex = workbook.getNumberOfSheets()-1;
            sheet = workbook.createSheet(sheetName, sheetIndex); //add behind
        }

        Integer row = 0;

        int col = -1;
        sheet.addCell(new Label(++col, row, "SN"));
        sheet.addCell(new Label(++col, row, "Account Name"));
        sheet.addCell(new Label(++col, row, "Currency"));
        sheet.addCell(new Label(++col, row, "Amount"));
        sheet.addCell(new Label(++col, row, "Created On"));

        for (JournalEntry s : summaries) {
            row++;

            //write data
            col = -1;
            sheet.addCell(new Label(++col, row, (row) + "."));
            sheet.addCell(new Label(++col, row, s.getAccount().getName()));
            sheet.addCell(new Label(++col, row, s.getCurrency().getCode()));
            sheet.addCell(new Label(++col, row, String.valueOf(s.getAmount())));
            sheet.addCell(new Label(++col, row, String.valueOf(s.getCreatedOn())));

        }
    }

基本上,它会读取JournalEntry实体的列表,并将特定值记录到Excel文件的行中。现在我必须像其他十几个实体那样做,每个实体都有不同的值要写下来。我如何将其变成通用函数并申请其他函数?

1 个答案:

答案 0 :(得分:1)

使用模板模式:

public abstract class SheetWriter<T> {
     private final void writeResultsIntoSheets(WritableWorkbook workbook, List<T> summaries) throws WriteException, RowsExceededException {
        String sheetName = getSheetName();

        WritableSheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            int sheetIndex = 0;
            if (workbook.getNumberOfSheets() > 0) sheetIndex = workbook.getNumberOfSheets()-1;
            sheet = workbook.createSheet(sheetName, sheetIndex); //add behind
        }

        int row = 0;
        writeHeadings(sheet, row);

        for (T s : summaries) {
            row++;
            writeRow(sheet, s, row);
        }
    }

    protected abstract String getSheetName();
    protected abstract void writeHeadings(WritableSheet sheet, int row) throws WriteException;
    protected abstract void writeRow(WritableSheet sheet, T item, int row) throws WriteException;
}

然后,为每个实体定义SheetWriter的子类并实现3个抽象方法。