0
点赞
收藏
分享

微信扫一扫

使用简单工厂模式代替多个else if

使用简单工厂模式代替多个else if

背景 推送当前数据到下移环节 除了状态发生改变 其他不变,通常使用多个else if 修改如下:

1.首先穿件一个PushDataFactory 工厂类

public class PushDataFactory {

    private static Map<String, PushData> punishMap = new HashMap<String,PushData>();

    private PushDataFactory() {}

    private static  final PushData EMPTY = new EmptyPushData();

    //获取
    public  static  PushData getPushData(String state) {
        PushData result = punishMap.get(state);
        return result == null ? EMPTY : result;
    }

    //将推送对象注册到这里
    public static  void registerPushData(String state,PushData o){
        punishMap.put(state, o);
    }

    private static  class EmptyPushData implements PushData {

        @Override
        public AjaxResult exePunish(OdsSignProject odsSignProject) {
            return null;
        }
    }
}

2.建pushData接口类

public interface PushData {
    AjaxResult exePunish(OdsSignProject odsSignProject);
}

3.controller层

@RestController
@RequestMapping("/pushData")
@CrossOrigin
public class PushDataController extends BaseController
{
    /**
     * 更新全过程步骤
     */
    @Log(title = "更新全过程步骤", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStep")
    public AjaxResult add(@RequestBody OdsSignProject odsSignProject){
        //得到签约状态
        String step=odsSignProject.getEvolve();

        //静态工厂类获取处罚对象
        PushData punish = PushDataFactory.getPushData(step);
        //执行逻辑
        return punish.exePunish(odsSignProject);
    }

}

4.创建实现类
目录结构
5.实现类如下: 每个不同的分类在afterPropertiesSet方法中定义即可 后期如果新增一个环节 在pushData下新增一个实现类即可

/**
 *   落地实现类
 * @Date 2021/12/27 10:23
 * @Version 1.0.0
 */
@Service
public class LandingPush implements PushData, InitializingBean {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private IOdsLandingProjectService iOdsLandingProjectService;

    @Override
    public AjaxResult exePunish(OdsSignProject odsSignProject)  {
        OdsLandingProject odsLandingProject =new OdsLandingProject();
        String code =odsSignProject.getCode();
        List<OdsLandingProject> odsLandingProject1 =iOdsLandingProjectService.selectOdsLandingProjectByCode(code);
        if (odsLandingProject1 !=null && odsLandingProject1.size() >0 ){
            return  AjaxResult.error("已存在更新记录,请勿重复更新");
        }else{
            //把签约类强制装换为landing类
            BeanUtils.copyProperties(odsSignProject,odsLandingProject);
            int flag=  iOdsLandingProjectService.insertOdsLandingProject(odsLandingProject);
            if (flag >0){
                return  AjaxResult.success("更新到落地环节成功");
            }else{
                return  AjaxResult.error("更新到落地环节失败");
            }
        }


    }

    @Override
    public void afterPropertiesSet() throws Exception {
        PushDataFactory.registerPushData("落地", this);
    }

}
举报

相关推荐

0 条评论