我正在开发一个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可以直接调用RowMappable,而不是内部类(InnerSimpleExcelIssueMapper),但如果这样做,最终用户(API用户)将能够调用mapRow方法。我不想在包之外调用mapRow,因为它会给最终用户(API用户)造成混乱。所以我用内部类的概念实现了它。
这样做对吗?是否有更好的方法来实现同样的目标?
这里有适用的design pattern吗?
发布于 2015-05-28 15:14:53
创建一个类,比如RowMappableImpl(在您的例子中是InnerSimpleExcelIssueMapper),实现RowMappable并实现返回Issue实例的方法mapRow()。
从ExcelColumn类中调用在RowMappableImpl中实现的mapRow()方法。这样,API的客户端就无法调用mapRow()。
https://stackoverflow.com/questions/30510332
复制相似问题