标签:list -- pst 不同的 spring ret 计算 runner 优惠
用户折扣计费运用
public interface CalculateStrategy { public String userType(); public double discount(double fee); }
几种不同的计费实现
普通用户
// 普通用户 @Service public class NormalStrategy implements CalculateStrategy{ @Override public String userType() { return "normal"; } @Override public double discount(double fee) { return fee * 1.0; } }
会员
@Service public class VipStrategy implements CalculateStrategy { @Override public String userType() { return "vip"; } @Override public double discount(double fee) { return fee * 0.8; } }
买的行为
@Service public class SaleService { HashMap<String, CalculateStrategy> calculateStrategyHashMap = new HashMap<>(); public SaleService(List<CalculateStrategy> calculateStrategyList) { // 托管给spring -- spring会给我们去创建对象 for (CalculateStrategy calculateStrategy : calculateStrategyList) { calculateStrategyHashMap.put(calculateStrategy.userType(), calculateStrategy); } } public double sale(String userType, double fee) { // 实际业务中: 计费优惠计算不是一行代码这么简单。 CalculateStrategy calculateStrategy = calculateStrategyHashMap.get(userType); fee = calculateStrategy.discount(fee); return fee; } }
测试
@RunWith(SpringRunner.class) @SpringBootTest public class DesignPatternApplication { @Autowired OrderService orderService; @Autowired SaleService saleService; @Test public void test1(){ double sale = saleService.sale("normal", 100); System.out.print(sale); } }
标签:list -- pst 不同的 spring ret 计算 runner 优惠
原文地址:https://www.cnblogs.com/Jomini/p/13047294.html