Java设计模式之策略模式+工厂模式+模板模式
Java设计模式之策略模式+工厂模式+模板模式
1.策略模式+工厂模式+模板模式
个人的理解:实际开发工程中,一些业务很复杂的逻辑使用很多的 if 或者 if···else 语句,不利于维护和扩展,为了使代码更加优雅,利于维护可以采用策略模式+工厂模式+模板模式设计模式
2.策略模式+工厂模式+模板模式优点
(1)、增强了系统的可扩展性。可以根据需要增加新的请求处理类,满足开闭原则。
3.代码实现
业务场景:根据计费方式计算出分润金额和返佣金额
(1)、定义接口 接口定义抽象方法,继承InitializingBean 的原因是重写afterPropertiesSet方法,将具体实现类注册到工厂类中。
/** * @author ppeng * @date 2020/9/21 10:49 * @description */ public interface CalHandler extends InitializingBean { /** * 分润金额计算 * @return */ BigDecimal calShareAmount(); /** * 返佣金额计算 * @return */ BigDecimal calCommissionAmount(); }
(2)、模板类
/** * @author ppeng * @date 2020/9/21 10:49 * @description * 定义模板类的作用: * 1.空实现接口方法,让实现类去实现所需要的抽象方法,否则接口新定义抽象方法,实现类必须实现该方法,不利于扩展 * 当然也可以使用JDK8默认方法或静态方法将公共的方法放到接口中写,但不推荐 * 2.公共方法可抽取到抽象类中复用 * */ public abstract class AbstractCalHandler implements CalHandler{ @Override public BigDecimal calShareAmount() { throw new UnsupportedOperationException(); } @Override public BigDecimal calCommissionAmount() { throw new UnsupportedOperationException(); } public BigDecimal common(){ System.out.println("调用抽象类公共方法"); return null; } }
(3)、定额计算(具体处理者)
/** * @author ppeng * @date 2020/9/21 10:51 * @description */ @Component public class FixAmountHandler extends AbstractCalHandler{ @Override public BigDecimal calShareAmount() { System.out.println("计算定额逻辑"); return new BigDecimal("1"); } @Override public void afterPropertiesSet() { HandlerCalFactory.register("1",this); } }
(4)、费率计算(具体处理者)
/** * @author ppeng * @date 2020/9/21 10:52 * @description */ @Component public class RateAmountHandler extends AbstractCalHandler{ @Override public BigDecimal calShareAmount() { System.out.println("计算比例逻辑"); return new BigDecimal("2"); } @Override public void afterPropertiesSet() throws Exception { HandlerCalFactory.register("2",this); } }
(5)、工厂类
/** * @author ppeng * @date 2020/9/21 10:53 * @description */ public class HandlerCalFactory { private static Map<String,CalHandler> map = new HashMap<String,CalHandler>(); public static void register(String key,CalHandler calHandler){ if(StringUtils.isEmpty(key) && null == calHandler){ return; } map.put(key,calHandler); } public static CalHandler getInvokeHandler(String key){ return map.get(key); } }
(6)、测试类
/** * @author ppeng * @date 2020/9/21 10:49 * @description */ public class Test { public static void main(String[] args) { CalHandler invokeHandler = HandlerCalFactory.getInvokeHandler("1"); BigDecimal bigDecimal = invokeHandler.calShareAmount(); } }
(6)、类关系图