【问题标题】:Java Design Pattern ApplyJava 设计模式应用
【发布时间】:2015-05-28 15:05:02
【问题描述】:

我正在开发一个 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适用吗?

【问题讨论】:

  • ExcelColumn类的API是什么?它应该逐行返回问题吗?
  • 它基本上是接受最终用户输入的类,应该给出Issue的对象

标签: java design-patterns


【解决方案1】:

创建一个类说RowMappableImpl(在你的情况下是InnerSimpleExcelIssueMapper),它实现RowMappable,并实现方法mapRow(),它返回一个Issue实例。

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

【讨论】:

  • 我已接受您对第一种方法的回答,但内部静态类无法访问外部类实例变量。请更正答案,以免其他读者得到错误信息。请refer this。所以如果我想使用内部类,这是我做的正确方法。
  • @VishalZanzrukia,对不起,我没有在 InnerSimpleExcelIssueMapper 类中看到对 descriptionColumnIndex 的引用。你是对的,那么它不能是静态内部类。我会编辑我的答案,谢谢!
猜你喜欢
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 2022-09-23
相关资源
最近更新 更多