直接附源码:
//订单生成类
public interface OrderService {
public void createOrder();
}
//订单生成业务类
package com.huanwu.sp.salecard.web.controller.ordertest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private PayMoney payMoney;
@Override
public void createOrder() {
double d = payMoney.getMoney("normal", 100);
System.out.println(d);
}
}
---策略模式,不同的类型,不同的折扣
//折扣接口
package com.huanwu.sp.salecard.web.controller.ordertest;
public interface DiscountService {
public String type();
public double discount(double fee);
}
//普通会员
package com.huanwu.sp.salecard.web.controller.ordertest;
import org.springframework.stereotype.Service;
@Service
public class NormalDiscount implements DiscountService {
@Override
public String type() {
return "normal";
}
@Override
public double discount(double fee) {
return fee * 0.9;
}
}
//vip会员
package com.huanwu.sp.salecard.web.controller.ordertest;
import org.springframework.stereotype.Service;
@Service
public class VipDiscount implements DiscountService {
@Override
public String type() {
return "vip";
}
@Override
public double discount(double fee) {
return fee * 0.8;
}
}
//计算折扣类
package com.huanwu.sp.salecard.web.controller.ordertest;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class PayMoney {
// public double getMoney(String type, double fee) {
// if ("normal".equals(type)) {
// // 如果是普通会员
// return fee * 1;
// } else if ("vip".equals(type)) {
// // 如果是vip会员
// return fee * 0.8;
// } else {
// return fee * 1.1;
// }
// }
//此处为最主要的一段代码
HashMap<String, DiscountService> map = new HashMap<>();
public PayMoney(List<DiscountService> list) {
for (DiscountService discountService : list) {
map.put(discountService.type(), discountService);
}
}
public double getMoney(String type, double fee) {
return map.get(type).discount(fee);
}
}