策略模式与工厂模式相结合

1、抽象策略类

public interface EnterAccountStrategy {

    /**
     * 入账接口,根据enterAccountType决定入账类型
     */
    void enterAccount(@Valid EnterAccountDTO enterAccountDTO) throws PostLoanException;

    boolean supports(RepayRuleEnum repayRuleEnum);

}

2、具体策略类

public class NormalEnterAccountHandler implements EnterAccountStrategy {...}

3、环境类

@Component
public class EnterAccountContext {

    @Autowired
    @Qualifier("RepaymentPlanEnterAccountServiceMap")
    Map<String, EnterAccountStrategy> maps;

    public void enterAccount(@Valid EnterAccountDTO enterAccountDTO) throws PostLoanException {
        getStrategy(enterAccountDTO.getEnterAccountType()).enterAccount(enterAccountDTO);
    }

    private EnterAccountStrategy getStrategy(RepayRuleEnum repayRuleEnum) throws PostLoanException {
        if (!CollectionUtils.isEmpty(maps)) {
            for (String key : maps.keySet()) {
                EnterAccountStrategy enterAccountStrategy = maps.get(key);
                if (enterAccountStrategy.supports(repayRuleEnum)) {
                    return enterAccountStrategy;
                }
            }
            throw new PostLoanException(ERROR, "没有对应的入账类型");
        } else {
            throw new PostLoanException(ERROR, ERROR_MSG);
        }
    }

}

getStrategy属于工厂方法 返回一个具体的策略类

4、客户端

@Autowired
EnterAccountContext enterAccountContext;
enterAccountContext.enterAccount(enterAccountDTO);

这样 新增 策略时 不会修改客户端

策略新增方法时 也不会修改客户端 只针对环境类修改即可 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值