概述
策略模式,笼统来讲,就是封装算法。
优点
1、算法可以自由切换。 2、避免使用if多重条件判断。 3、扩展性良好。
缺点
1、策略类膨胀,如果策略很多 ,维护也比较困难 todo
2、所有策略类都需要对外暴露。
使用场景
比较常见的天猫88VIP,88VIP购买商品是95折,普通用户无折扣,将来再来一个SVIP ,假如现在要设计一套报价系统,针对不同用户返回不同价格,就可以用到策略模式。
使用教程
新建策略抽象接口,每种会员都建立一个标识,分别是 “Normal”,“VIP”,“SVIP”
public interface IDiscount {
/**
* 获取策略类型, “Normal”,“VIP”,“SVIP”
*/
String getType();
/**
* 计算金额
*/
Double discount(double cost);
}
3种具体策略实现该接口
普通会员 无折扣
@Service
public class NormalDiscount implements IDiscount {
@Override
public String getType() {
return "Normal";
}
@Override
public Double discount(double cost) {
return cost;
}
}
VIP 95折
@Service
public class VipDiscount implements IDiscount {
@Override
public String getType() {
return "VIP";
}
@Override
public Double discount( double cost) {
System.out.println("use VipDiscount");
return cost * 0.95;
}
}
SVIP
@Service
public class SvipDiscount implements IDiscount {
@Override
public String getType() {
return "SVIP";
}
@Override
public Double discount( double cost) {
System.out.println("use SvipDiscount");
return cost * 0.5;
}
}
封装service对外提供服务
@Component
public class PayService {
static Map<String, IDiscount> map =new HashMap<>();
@Autowired
List<IDiscount> discounts = new ArrayList<>();
/**
* 1.有参构造方法是可以
* 2.@auto注解也可以,在执行完构造方法以后
*/
public PayService(List<IDiscount> list) {
for(IDiscount iDiscount:list){
map.put(iDiscount.getType(),iDiscount);
}
}
public double payDiscount(String type, double cost){
System.out.println(map.size());
return map.get(type).discount(cost);
}
}
我是通过controller来测试
@RequestMapping("discount")
public String discount(@RequestParam(name = "type",required = false) String type){
double result = payService.payDiscount(type,100) ;
return "您是" +type + "会员,享受的价格为 " + result;
}
总结
策略模式就好比诸葛亮的锦囊妙计,每一个锦囊都是一种解决方案。
就像出行的方式有很多种,高铁,飞机,大巴等待,根据一定条件来选择具体策略。