优点:
未使用if else,就算以后增加支付类型,也不用改动之前代码
只需要新写一个支付类,给添加自定义注解@Pay
首先:
定义自定义注解 Pay
定义 CMBPay ICBCPay 两种支付 根据注解中的value 标识是哪种支付(1为CMBPay 2为ICBCPay)
两种支付都需继承InitNewService.java 避免注入对象报错
package com.huarui.inter; import java.math.BigDecimal; /** * 支付需实现该接口 * 接口编程: */ public interface Strategy { /** * 计算支付金额 通过渠道id和商品id 进行价格计算 * @param channelId * @param goodsId * @return */ BigDecimal calRecharge(Integer channelId,Integer goodsId); }
package com.huarui.pay; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) //注解定义到类上 @Retention(RetentionPolicy.RUNTIME) //生命周期 public @interface Pay { int value(); }
@Pay(2) public class ICBCPay extends InitNewService implements Strategy { @Override public BigDecimal calRecharge(Integer channelId, Integer goodsId) { //通过渠道id查询优惠折扣 //通过商品id查询商品价格 //返回商品最终价格 return new BigDecimal(100); } }