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,带您进群互相学习
左侧小编微信,右侧获取免费资料
- Java 设计模式学习代码 https://github.com/Dylan-haiji/design-pattern
- SpringCloud学习代码: https://github.com/Dylan-haiji/javayh-cloud
- AlibabaCloud学习代码:https://github.com/Dylan-haiji/javayh-cloud-nacos
- SpringBoot+Mybatis 多数据源切换:https://github.com/Dylan-haiji/javayh-boot-data-soure
- Redis、Mongo、Rabbitmq、Kafka学习代码: https://github.com/Dylan-haiji/javayh-middleware
- SpringBoot+SpringSecurity实现自定义登录学习代码:https://github.com/Dylan-haiji/javayh-distribution