策略模式--导出实战
需求说明
WKD项目中导出使用到了策略模式,需要根据id导出不同订单的明细数据,其中订单类型有四种(直营返货调拨单/申请单,加盟返货调拨单/申请单),使用策略模式避免使用多重条件判断(if,else),美化代码的同时增加了扩展性。
策略接口
public interface IExportStrategy { /** * 根据id导出相应订单类型(直营返货申请单/调拨单,加盟返货申请单/调拨单,共四种类型,用ABCD表示)的数据 * @param id * @return */ List makeExportData(Long id); }
实现了策略接口的实体策略类
public class AExportStrategyImpl implements IExportStrategy { @Override public List makeExportData(Long id) { //根据id查询数据 xxx queryList = xxxServer.queryById(id) //最终需要导出的excel数据 List excelList = new ArrayList(); ...... //对查询出来的数据queryList做业务处理后,赋值到excelList ...... return excelList; } }
说明还有类似的B,C,D三个实体策略类,类似AExportStrategyImpl,只是makeExportDate(Long id)中的实现不同.
策略工厂
/** * 生产具体策略工厂 * @author 佛大java程序员 * @create 2020/5/6 * @since 1.0.0 */ public class StrategyFactory { public static IExportStrategy getStrategy(String type){ IExportStrategy strategy = null; try { //根据订单的类型(A,B,C,D),找到类型Type对应枚举类的策略实现类的类全名,再通过反射获得具体策略类实现类对象实例 strategy = (IExportStrategy) Class.forName(ExportStrategyClazzEnums.getDesc(type)).newInstance(); } catch (Exception e) { e.printStackTrace(); System.out.println("生成策略出错"); } return strategy; } }
策略实现类枚举
/** * 具体策略实现类枚举 * @author 佛大Java程序员 * @create 2020/05/6 * @since 1.0.0 */ public enum ExportStrategyClazzEnums { /** * 申请单直营返货 */ APPLY_DIRECT_RETURN("A","com.whl.impl.AExportStrategyImpl"), /** * 调拨单直营返货 */ ORDER_DIRECT_RETURN("B","com.whl.impl.BExportStrategyImpl"), /** * 申请单加盟返货 */ APPLY_FRANCHISEE_RETURN("C","com.whl.impl.CExportStrategyImpl"), /** * 调拨单直营返货 */ ORDER_FRANCHISEE_RETURN("D","com.whl.impl.DExportStrategyImpl"); /** * 调拨申请状态 */ private String type; /** * 调拨申请状态说明 */ private String desc; public static String getDesc(String type) { for (ExportStrategyClazzEnums clazzEnum : ExportStrategyClazzEnums.values()) { if (clazzEnum.getType().equals(type)) { return clazzEnum.getDesc(); } } return null; } ExportStrategyClazzEnums(String type, String desc) { this.type = type; this.desc = desc; } /** * 获取类型 * * @return */ public String getType() { return type; } /** * 设置类型 * * @param type */ public void setType(String type) { this.type = type; } /** * 获取类型说明 * * @return */ public String getDesc() { return desc; } /** * 设置类型说明 * * @param desc */ public void setDesc(String desc) { this.desc = desc; } }
实现类
/** * @author 佛大Java程序员 * @create 2020/05/6 * @since 1.0.0 */ @Service public class ExportServiceImpl implements IExportService { /** * 导出申明明细列表到OSS上 * @param threadId * @return */ @Override public String exportApplyList(Long threadId,ExportReqDto reqDto){ long t1 = System.currentTimeMillis(); //直营_调配补返_状态 String type = "APPLY_"+reqDto.getManageType()+"_"+reqDto.getTransferType();
//根据订单类型获取到具体的策略实现类 IExportStrategy strategy = StrategyFactory.getStrategy(type);
//调用接口方法 List excelList = strategy.makeExportData(reqDto.getId()); String fileName = "申请明细列表_"+threadId+".xls"; return exportExcelToOss(t1,fileName,excelList,null); } }
参考/好文:
菜鸟教程 --
https://www.runoob.com/design-pattern/strategy-pattern.html