Java设计模式应用

时间:2015-05-28 15:05:03

标签: java design-patterns

我正在开发一个API,其中包含以下代码。

RowMappable.java

package com.api.mapper;
import org.apache.poi.ss.usermodel.Row;
public interface RowMappable<T> {
  T mapRow(Row row);
}

Issue.java

package com.api.pojo;

import org.apache.poi.ss.usermodel.Cell;

/**
 * It will contain all the fields related to Issue.
 * 
 * @author vishal.zanzrukia
 * 
 */
public class Issue {

  private Cell description;

  /**
   * @return
   */
  public String getDescription() {
    if (description != null) {
      return description.getStringCellValue();
    }
    return null;
  }

  /**
   * @param description
   */
  public void setDescription(Cell description) {
    this.description = description;
  }
}

ExcelColumn.java

package com.api.excel;

import org.apache.poi.ss.usermodel.Row;
import com.api.mapper.SimpleExcelIssueMapper;
import com.api.pojo.Issue;


/**
 * @author vishal.zanzrukia
 * 
 */
public class ExcelColumn {

  private int descriptionColumnIndex;

  /**
   * This is inner class to protect visibility of mapRow method
   * 
   * @author vishal.zanzrukia
   *
   */
  class InnerSimpleExcelIssueMapper implements RowMappable<Issue> {

    @Override
    public Issue mapRow(Row row) {
      Issue issue = new Issue();
      issue.setDescription(row.getCell(descriptionColumnIndex));
      return issue;
    }
  }

  /**
   * set issue description column index<BR>
   * <STRONG>NOTE :</STRONG> index starts from <STRONG>0</STRONG>
   * 
   * @param descriptionColumnIndex
   */
  public void setDescriptionColumnIndex(int descriptionColumnIndex) {
    this.descriptionColumnIndex = descriptionColumnIndex;
  }
}

此处,ExcelColumn是最终用户(API用户)将用于映射excel列索引及其目的的类(此处,例如,它的描述)。

现在,ExcelColumn可以implements直接发送到RowMappable而非内部类(InnerSimpleExcelIssueMapper),但如果我这样做,最终用户(API用户)将能够调用mapRow方法。我不想在包裹外面调用mapRow因为它会给最终用户(API用户)造成混淆。所以我用内部类概念实现了它。

这是正确的方法吗?有没有更好的方法来实现同样的目标?

这里有适用的design pattern吗?

1 个答案:

答案 0 :(得分:1)

创建一个实现RowMappableImpl的类InnerSimpleExcelIssueMapper(在您的情况下为RowMappable)并实现返回mapRow()实例的方法Issue

ExcelColumn课程中,调用mapRow()中实施的RowMappableImpl方法。这样API的客户就无法拨打mapRow()