Java 应用设计模式

Java Design Pattern Apply

我正在开发一个 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 列索引及其目的的 class(这里是描述例如)。

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

这是正确的做法吗?有没有更好的方法来达到同样的效果?

这里有design pattern适用的吗?

创建一个实现 RowMappable 的 class say RowMappableImpl(在你的例子中 InnerSimpleExcelIssueMapper)并实现 mapRow() 方法 returns一个 Issue 实例。

从您的 ExcelColumn class 调用 mapRow() 方法,该方法在 RowMappableImpl 中实现。这样 API 的客户端将无法调用 mapRow().