需求
针对店下商铺,有这样一个需求,对用户客户分为了普通客户、vip客户、超级vip用户、专属vip用户4个等级,每当用户购买商品时,针对不同的用户等级和消费金额采取不同的打折优惠策略。在平常的开发当中,必然会出现多层的if-else嵌套判断,先判断用户的等级再判断用户购买商品的消费金额。
弊端
以上的情况出现了多层的if-else嵌套,除此之外,以后如果需求再有变动,需要再增加一个用户等级,那么又会再次添加if-else的嵌套判断,那么如何解决上述的弊端呢,采用策略模式和工厂模式的搭配使用,可以很好地优化多层if-else的多层嵌套
实现
编写用户等级枚举类
package com.zbiti.ifelse.UserType;
/**
* 用户类型枚举类
*/
public enum UserPayServiceEnum {
VIP(1,"Vip"),
SUPERVIP(2,"SuperVip"),
PARTICULALYVIP(3,"ParticularlyVip"),
NORMAL(4,"NormalPayService");
/**
* 状态值
*/
private int code;
/**
* 类型描述
*/
private String value;
private UserPayServiceEnum(int code, String value) {
this.code = code;
this.value = value;
}
public int getCode() {
return code;
}
public String getValue() {
return value;
}
public static UserPayServiceEnum valueOf(int code) {
for (UserPayServiceEnum type : UserPayServiceEnum.values()) {
if (type.getCode()==code) {
return type;
}
}
return null;
}
public static void main(String[] args) {
System.out.println(UserPayServiceEnum.VIP.getValue());
}
}
编写不同的用户等级策略类
以