呆呆槑~
2021-12-02 16:17
采纳率: 0%
浏览 77

策略模式+springboot动态调用多个实现类

相关代码

策略类:

public AssetComplexService getService(Integer type) {
        if(type == null){
            log.error("获取对应实现类失败");
        }
        strategyMap.put(1,assetReceiveService);
        strategyMap.put(2,assetBorrowService);
        strategyMap.put(3,assetReturnService);
        strategyMap.put(4,assetSendbackService);
        return strategyMap.get(type);
    }

实现类1:

@Service("assetReceiveService")
public class AssetReceiveServiceImpl extends ServiceImpl<AssetComplexDao, AssetComplexDO> implements AssetComplexService{....}

实现类2:

@Service("assetBorrowService")
public class AssetBorrowServiceImpl extends ServiceImpl<AssetComplexDao, AssetComplexDO> implements AssetComplexService{....}

实现类3:

@Service("assetReturnService")
public class AssetReturnServiceImpl extends ServiceImpl<AssetComplexDao, AssetComplexDO> implements AssetComplexService{....}

实现类4:

@Service("assetSendbackService")
public class AssetSendbackServiceImpl extends ServiceImpl<AssetComplexDao, AssetComplexDO> implements AssetComplexService{....}

controller类:

public class AssetComplexController {
    
        @Autowired
        AssetService assetService;
        @Autowired
        Factory factory;
    
    @ApiOperation("分页列表")
    @PostMapping("/list")
    public Result<IPage<AssetComplexDO>> list(@RequestBody SearchCommonDTO<?> params, int type){
        Result<IPage<AssetComplexDO>> result = new Result<>();
        AssetComplexService assetComplexService = factory.getService(type);
        result.setResult(assetComplexService.queryPage(params,type));
        return result;
    }

问题:

策略模式自动注入的map:
Map<String,UserService> map;
这里的String怎么优化?
1、用枚举的话,每次新增一个需求还得再更新一些这个枚举类?那就跟一个个put进去一样。
2、每个策略类(实现类)里写一个getUserType方法,但是也得先判断类型才能进入这个策略类(实现类)呀。

想要实现的效果:

新的相同的需求出现的时候,不需要修改我的原有代码(所有),只需新增一个实现类并重写那些方法就行;
传入的type参数为int,而不是String。
万分感谢!

5条回答 默认 最新

相关推荐 更多相似问题