if else 舊代碼
public BigDecimal calPrice(BigDecimal orderPrice, String buyerType) {
if (用戶是專屬會員) {
if (訂單金額大於30元) {
returen 7折價格;
}
}
if (用戶是超級會員) {
return 8折價格;
}
if (用戶是普通會員) {
if(該用戶超級會員剛過期並且尚未使用過臨時折扣){
臨時折扣使用次數更新();
returen 8折價格;
}
return 9折價格;
}
return 原價;
}
第一次解決:加策略模式
public interface UserPayService {
/**
* 計算應付價格
*/
public BigDecimal quote(BigDecimal orderPrice);
}
public class ParticularlyVipPayService implements UserPayService {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
if (消費金額大於30元) {
return 7折價格;
}
}
}
public class SuperVipPayService implements UserPayService {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
return 8折價格;
}
}
public class VipPayService implements UserPayService {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
if(該用戶超級會員剛過期並且尚未使用過臨時折扣){
臨時折扣使用次數更新();
returen 8折價格;
}
return 9折價格;
}
}
public class Test {
public static void main(String[] args) {
UserPayService strategy = new VipPayService();
BigDecimal quote = strategy.quote(300);
System.out.println("普通會員商品的最終價格爲:" + quote.doubleValue());
strategy = new SuperVipPayService();
quote = strategy.quote(300);
System.out.println("超級會員商品的最終價格爲:" + quote.doubleValue());
}
}
第二次:加入工廠模式和Spring Bean的註冊
- 工廠模式
public class UserPayServiceStrategyFactory {
private static Map<String,UserPayService> services = new ConcurrentHashMap<String,UserPayService>();
public static UserPayService getByUserType(String type){
return services.get(type);
}
public static void register(String userType,UserPayService userPayService){
Assert.notNull(userType,"userType can't be null");
services.put(userType,userPayService);
}
}
public BigDecimal calPrice(BigDecimal orderPrice,User user) {
String vipType = user.getVipType();
UserPayService strategy = UserPayServiceStrategyFactory.getByUserType(vipType);
return strategy.quote(orderPrice);
}
- Spring Bean的註冊
@Service
public class ParticularlyVipPayService implements UserPayService,InitializingBean {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
if (消費金額大於30元) {
return 7折價格;
}
}
@Override
public void afterPropertiesSet() throws Exception {
UserPayServiceStrategyFactory.register("ParticularlyVip",this);
}
}
@Service
public class SuperVipPayService implements UserPayService ,InitializingBean{
@Override
public BigDecimal quote(BigDecimal orderPrice) {
return 8折價格;
}
@Override
public void afterPropertiesSet() throws Exception {
UserPayServiceStrategyFactory.register("SuperVip",this);
}
}
@Service
public class VipPayService implements UserPayService,InitializingBean {
@Override
public BigDecimal quote(BigDecimal orderPrice) {
if(該用戶超級會員剛過期並且尚未使用過臨時折扣){
臨時折扣使用次數更新();
returen 8折價格;
}
return 9折價格;
}
@Override
public void afterPropertiesSet() throws Exception {
UserPayServiceStrategyFactory.register("Vip",this);
}
}
總結
個人覺得這個MAP起到很重要的作用 以及策略和工廠模式