SPRING中策略模式使用的正确姿态
1.策略模式简介
策略模式:策略模式是一种可以代替大量代码if-else的利器,应用场景较多:比如 支付(微信支付,支付宝支付,银行开支付),整合电商平台解密(pdd解密,dj解密,淘宝解密),策略模式对外提供统一解决方案的入口,具体解决策略自己选择适配; 咱们经常听到的段子是某cto怒怼开发人员谁再写if-else扣工资1000,可见高层是多么痛恨if-else,所以策略模式在对降低项目的整理耦合度,减少项目的维护成本显得尤为重要。
2.策略模式的使用
在上述简介中的场景咱们任取一个, 比如在物流项目中,整合各个电商平台然后进行订单收件人信息解密策略。
(1)定义策略接口
public interface IDecryptStrategyService {
/**
* 做解密操作
*
* @param order 订单数据
*/
void doDecrypt(Order order);
}
(2)实现定义的策略的具体实现
@Service
public class PddDecryptStrategyService implements IDecryptStrategyService {
/**
* 做解密操作
*
* @param order 订单信息
*/
public void doDecrypt(OrderInfo order) {
doSomthing();
}
}
@Service
public class JdDecryptStrategyService implements IDecryptStrategyService {
/**
* 做解密操作
*
* @param order 订单信息
*/
public void doDecrypt(OrderInfo order) {
doSomthing(order);
}
}
(4)实现定义的策略选择器的实现
@Service
public class DecryptStrategySelector {
@Autowired
private Map<String, IDecryptStrategyService> decryptStrategyServiceMap;
public void doDecrypt(OrderInfo order) {
// 获取策略名称map
Map<String, String> strategyMap = Enums.PlantDecryptStrategyEnum.getMap();
// 获取策略名称
String strategyName = strategyMap.get(order.getPlantCode);
// 获取策略
IDecryptStrategyService decryptStrategyService = decryptStrategyServiceMap.get(strategyName);
// 执行策略
decryptStrategyService.doDecrypt(order);
}
}
public class Enums {
public enum PlantDecryptStrategyEnum {
PDD("PDD", "pddDecryptStrategyService");
JD("JD", "jdDecryptStrategyService");
private String code;
private String strategyName;
PlantDecryptStrategyEnum(String code, String strategyName) {
this.setCode(code);
this.setStrategyName(strategyName);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getStrategyName() {
return strategyName;
}
public void setStrategyName(String strategyName) {
this.strategyName = strategyName;
}
private static Map<String, String> map = new HashMap<>();
static {
map.put(PDD.code, PDD.strategyName);
}
public static Map<String, String> getMap() {
return map;
}
}
}
以上是在spring中如何使用策略模式
3.总结
(1)以上的策略模式案例相对来说不并不复杂,主要的逻辑都是体现在关于不同平台的解密策略上。结构相对来说也⽐较简单,在实际的开发中这样的设计模式也是⾮常常⽤的。另外这样的设计与命令模式、适配器模式结构相似,但是思路是有差异的。
(2)通过策略设计模式的使⽤可以把我们⽅法中的if语句优化掉,⼤量的if语句使⽤会让代码难以扩展,也不好维护,同时在后期遇到各种问题也很难维护。在使⽤这样的设计模式后可以很好的满⾜隔离性与和扩展性,对于不断新增的需求也⾮常⽅便承接。
(3)策略模式 、 适配器模式 、 组合模式 等,在⼀些结构上是⽐较相似的,但是每⼀个模式是有⾃⼰的逻辑特点,在使⽤的过程中最佳的⽅式是经过较多的实践来吸取经验,为后续的研发设计提供更好的技术输出。