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);
这样 新增 策略时 不会修改客户端
策略新增方法时 也不会修改客户端 只针对环境类修改即可