需求:商品有三种折扣价,普通客户不享受任何优惠,vip客户享受9折优惠,超级vip客户享受8折优惠
当没有用到设计模式时,我们一般会采用下面的方式处理业务
int type = 1;
if(type == 1){
System.out.println("普通客户,商品原价出售");
}else if(type == 2){
System.out.println("vip客户,商品9折出售");
}else if(type == 3){
System.out.println("超级vip客户,商品8折出售");
}
这样做的好处是直观,能以下看懂其中的逻辑关系,但是弊端更多,当要推出第四种优惠活动时,我们不得不改变源码,重新加else-if 判断语句,这样不符合开发开闭原则,耦合性太大,这时可以用策略模式来解决该问题。
抽象策略类
public interface CustomerStrategy {
//策略方法
public double discountPrice(double orgnicPrice);
}
具体策略类
/**
* 普通客户
*/
public class OrgnicCustomer implements CustomerStrategy {
@Override
public double discountPrice(double orgnicPrice) {
return orgnicPrice;
}
}
/**
* vip客户
*/
public class VipCustomer implements CustomerStrategy {
@Overr