设计模式(一)-接口使用场景

 

用户折扣计费运用

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);
	}
	

}

  

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-06-04 23:49  抽象Java  阅读(298)  评论(0编辑  收藏  举报