使用工厂方法模式:
public enum ReportType {EXCEL, CSV};@Servicepublic class ReportFactory { @Resource private ExcelReport excelReport; @Resource private CSVReport csvReport public Report forType(ReportType type) { switch(type) { case EXCEL: return excelReport; case CSV: return csvReport; default: throw new IllegalArgumentException(type); } }}enum当您使用以下命令调用控制器时,Spring可以创建报告类型
?type=CSV:
class MyController{ @Resource private ReportFactory reportFactory; public HttpResponse getReport(@RequestParam("type") ReportType type){ reportFactory.forType(type); }}但是,
ReportFactory它非常笨拙,并且每次添加新报告类型时都需要进行修改。如果报告类型列表已修复,则可以。但是,如果您计划添加越来越多的类型,这将是一个更可靠的实现:
public interface Report { void generateFile(); boolean supports(ReportType type);}public class ExcelReport extends Report { publiv boolean support(ReportType type) { return type == ReportType.EXCEL; } //...}@Servicepublic class ReportFactory { @Resource private List<Report> reports; public Report forType(ReportType type) { for(Report report: reports) { if(report.supports(type)) { return report; } } throw new IllegalArgumentException("Unsupported type: " + type); }}通过此实现,添加新的报表类型就像添加新的bean实现
Report和新的
ReportType枚举值一样简单。您可以不使用
enum和使用字符串(甚至可能是bean名称)而无所事事,但是我发现强烈键入很有用。
最后的想法:
Report名字有点不幸。
Report类表示(无状态?)某种逻辑的封装(策略模式),而名称则表示它封装了
值 (数据)。我会建议
ReportGenerator这样的。



