设计模式之策略模式

概述

策略模式,笼统来讲,就是封装算法。

优点

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;
    }

在这里插入图片描述

总结

策略模式就好比诸葛亮的锦囊妙计,每一个锦囊都是一种解决方案。
就像出行的方式有很多种,高铁,飞机,大巴等待,根据一定条件来选择具体策略。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值