栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

有条件地注入豆

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

有条件地注入豆

使用工厂方法模式:

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
这样的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498221.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号