对于业务代码中有多个if时,可以采用策略模式,将多个if里的算法封装为多个处理器(handler),再通过工厂方法去获取相应的处理器。
如果if里的算法有共同特征,提取为抽象方法,handler去继承实现。
/** * 打折模板 * @author XinHai.Ma * */ public class Discount { /** * 打折方法 * @return */ public String discount() { return null; } }
/** * 初级会员打折策略 * @author XinHai.Ma * */ public class PrimaryMember extends Discount { @Override public String discount() { return "0.8"; } }
/** * 中级会员打折策略 * @author XinHai.Ma * */ public class IntermediateMember extends Discount { @Override public String discount() { return "0.7"; } }
/** * 高级会员打折策略 * @author XinHai.Ma * */ public class AdvancedMember extends Discount { @Override public String discount() { return "0.6"; } }
import java.math.BigDecimal; /** * 类描述: 价格类 * @Author: XinHai.Ma * @Date: 2020/8/23 14:51 */ public class Price { /** * 打折策略对象 */ private Discount discount; public Price(Discount discount) { this.discount = discount; } /** * 计算价格 * @param amount * @param discount * @return */ public double calculation(String amount, String discount) { //原价 BigDecimal originalPrice = new BigDecimal(amount); //会员折扣 BigDecimal memberDiscount = new BigDecimal(discount); return originalPrice.multiply(memberDiscount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
/** * 类描述: 折扣工厂 * @Author: XinHai.Ma * @Date: 2020/8/23 15:05 */ public class DiscountFactory { private DiscountFactory() {} /** * 功能描述: 根据用户等级获取折扣 * @Param: [member] * @Return: www.maxinhai.com.Discount * @Author: 15735400536 * @Date: 2020/8/23 15:04 */ public static Discount getDiscount(String member) { Discount discount = null; switch (member) { case "普通会员": discount = new PrimaryMember(); case "中级会员": discount = new IntermediateMember(); case "高级会员": discount = new AdvancedMember(); } return discount; } }
public class PriceDemo { public static void main(String[] args) { Discount discount = DiscountFactory.getDiscount("中级会员"); Price price = new Price(discount); String amount = "216.8"; double calculation = price.calculation(amount, discount.discount()); System.out.println("优惠折扣: " + discount.discount()); System.out.println("打折后价格: " + calculation); } }