Java设计模式之策略模式

Java设计模式相关文章

1. Java设计模式之模板模式
2. Java设计模式之策略模式
3. Java设计模式之工厂模式
4. Java设计模式之装饰者模式
5.Java设计模式之单例模式
Java 设计模式源代码,欢迎star
https://github.com/Dylan-haiji/design-pattern

概念

策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

优缺点

  • 主要优点如下:
    a) 多重条件语句不易维护,而使用策略模式可以避免使用多重条件语句。
    b) 策略模式提供了一系列的可供重用的算法族,恰当使用继承可以把算法族的公共代码转移到父类里面,从而避免重复的代码。
    c) 策略模式可以提供相同行为的不同实现,客户可以根据不同时间或空间要求选择不同的。
    d) 策略模式提供了对开闭原则的完美支持,可以在不修改原代码的情况下,灵活增加新算法。
    e) 策略模式把算法的使用放到环境类中,而算法的实现移到具体策略类中,实现了二者的分离。
  • 主要缺点如下:
    a) 客户端必须理解所有策略算法的区别,以便适时选择恰当的算法类。
    b) 策略模式造成很多的策略类。

代码演示

场景设定

策略模式场景设定的具体介绍 https://github.com/Dylan-haiji/design-pattern/tree/master/strategist-mode

结构图

在这里插入图片描述

3.1 定义策略接口

public interface PriceService {

    Map<String, PriceService> map = new ConcurrentHashMap<>();
    @PostConstruct
    default void init() {
        map.put(this.getCustomerType(), this);
    }
    /**
     * @Description 根据用户计算价格
     * @UserModule: design-pattern
     * @author Dylan
     * @date 2020/2/2 0002
     * @param [priceVO]
     * @return PriceDTO
     */
    PriceDTO getPrice(PriceVO priceVO);

    /**
     * @Description 确定类型
     * @UserModule: design-pattern
     * @author Dylan
     * @date 2020/2/2 0002
     * @param []
     * @return java.lang.String
     */
    String getCustomerType();
}

3.2 定义上下文获取策略

public class CustomerContext {
    private PriceService priceService;

    public CustomerContext(String customerType) {
        this.priceService = PriceService.map.get(customerType) ;
    }

    public PriceDTO getPrice(PriceVO priceVO){
        return priceService.getPrice(priceVO);
    }
}

3.3 实现策略

@Service
public class VipService implements PriceService {

    @Override
    public PriceDTO getPrice(PriceVO priceVO) {
        String price = BigDecimalUtils.calculation(priceVO.getPrice(), 0.7);
        String priceEms = BigDecimalUtils.calculation(priceVO.getEmsPrice(), 0.7);
        return PriceDTO.builder().type(priceVO.getType()).price(price).emsPrice(priceEms).msg(Constant.MSG).build();
    }

    @Override
    public String getCustomerType() {
        return Constant.VIP;
    }
}

3.4 应用

 @PostMapping(value = "/getPrice")
    public DataResult getPrice(@RequestBody PriceVO vo){
        CustomerContext customerContext = new CustomerContext(vo.getType());
        return DataResult.success(customerContext.getPrice(vo));
    }

3.5 验证

访问接口 http://localhost:8090/strategist/getPrice
在这里插入图片描述

关注 Java有货领取更多资料

联系小编。微信:372787553,带您进群互相学习
左侧小编微信,右侧获取免费资料
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小杨同学~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值