有一个需求,导入Excel文件对文件进行解析(多种解析方式),用户在界面上可以下拉选择解析的方式。解决办法首先想到应该就是根据用户的选择判断调用哪个解析方法。因为这些解析方式重用可能性比较大,我们用接口的方式来实现它。
接口:
实现类A:
实现类B:
Service:
测试类:
输出:
用户选择使用A方法解析Excel !
{way_b=选择B类解析, way_a=选择A类解析}
Service中提供了getMapSelect()方法用于返回一个Map用于用户在界面直接选择解析方式。如果需要增加解析方式,只需要实现接口即可,无需更改其它代码。界面下拉项目会根据实现类的个数自动显示。不好的地方就是需要通过(ApplicationContext 获取接口的实现的实例
会有入侵式设计。
接口:
public interface ExcelImport {
/**
* 返回实现类标识
*
* @return
*/
public String getId();
/**
* 返回实现类名称可用于界面下拉选择
*
* @return
*/
public String getName();
/**
* 解析Excel
*/
public void analyze();
}
实现类A:
@Service
public class ExcelImportAImpl implements ExcelImport {
private static final String id = "way_a";
private static final String name = "选择A类解析";
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public void analyze() {
System.out.println("用户选择使用A方法解析Excel !");
}
}
实现类B:
@Service
public class ExcelImportBImpl implements ExcelImport {
private static final String id = "way_b";
private static final String name = "选择B类解析";
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public void analyze() {
System.out.println("用户选择使用B方法解析Excel !");
}
}
Service:
@Service("excelImportService")
public class ExcelImportService implements ApplicationContextAware {
private ApplicationContext applicationContext;
//注意线程安全问题(这边不会多次设置值不做处理了)
private Map<String, ExcelImport> map = new HashMap<String, ExcelImport>();
//注意线程安全问题(这边不会多次设置值不做处理了)
private Map<String, String> mapForSelect = new HashMap<String, String>();
private List<String> list = new ArrayList<String>();
/**
* 根据用户选择返回对应的解析实现类
*
* @param key 实现类的标识
* @return
*/
public ExcelImport getExcelImportEntity(String key) {
return this.map.get(key);
}
/**
* 返回用于界面选择
*
* @return
*/
public Map<String, String> getMapSelect() {
return mapForSelect;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
for (ExcelImport entity : this.applicationContext.getBeansOfType(ExcelImport.class).values()) {
map.put(entity.getId(), entity);
mapForSelect.put(entity.getId(), entity.getName());
}
}
}
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:beans.xml"})
public class TestImport {
@Autowired
private ExcelImportService excelImportService;
@Test
public void test() {
excelImportService.getExcelImportEntity("way_a").analyze();
System.out.println(excelImportService.getMapSelect());
}
}
输出:
用户选择使用A方法解析Excel !
{way_b=选择B类解析, way_a=选择A类解析}
Service中提供了getMapSelect()方法用于返回一个Map用于用户在界面直接选择解析方式。如果需要增加解析方式,只需要实现接口即可,无需更改其它代码。界面下拉项目会根据实现类的个数自动显示。不好的地方就是需要通过(ApplicationContext 获取接口的实现的实例
会有入侵式设计。