在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。简单理解就是创建一个 context 对象,动态的选择运行时的策略。
spring cloud security中SecurityContext 保存策略的实现
SecurityContext 是 Spring Security 中的安全上下文, 绑定了当前请求中的认证信息Authentication ,提供了当前用户的认证信息以及角色权限等内容 。接口SecurityContextHolderStrategy定义了SecurityContext 的保存策略。代码如下:
public interface SecurityContextHolderStrategy {
/**
* 获取SecurityContext
*/
SecurityContext getContext();
/**
*保存SecurityContext
*/
void setContext(SecurityContext context);
}
接口SecurityContextHolderStrategy,其实现类如下:
GlobalSecurityContextHolderStrategy,全局保存策略,全部请求使用一个 SecurityContext。
ThreadLocalSecurityHolderStrategy,主要通过 Thread Local 将 SecurityCont巳xt 与当前访问的线程进行绑定。
InheritableThreadLocalSecurityContextHolderStrategy,与 ThreadLocalSecurityHolderStrategy
类似,但是支持从父线程中存取 SecurityContext。
SecurityContextHolder类,实现了策略动态初始化,代码如下:
public class SecurityContextHolder {
public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL";
public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL";
public static final String MODE_GLOBAL = "MODE_GLOBAL";
public static final String SYSTEM_PROPERTY = "spring.security.strategy";
private static String strategyName = System.getProperty(SYSTEM_PROPERTY);
private static SecurityContextHolderStrategy strategy;
static {
initialize();
}
/**
* 策略初始化
*/
private static void initialize() {
if (!StringUtils.hasText(strategyName)) {
// Set default
strategyName = MODE_THREADLOCAL;
}
if (strategyName.equals(MODE_THREADLOCAL)) {
strategy = new ThreadLocalSecurityContextHolderStrategy();
}
else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) {
strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
}
else if (strategyName.equals(MODE_GLOBAL)) {
strategy = new GlobalSecurityContextHolderStrategy();
}
else {
// Try to load a custom strategy
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (SecurityContextHolderStrategy) customStrategy.newInstance();
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
}
}
}
价格计算策略的实现
在打车费用的价格的计算中,高速费和路桥费,属于固定价格计算策略。时长费和里程费,属于价格x价格单位的乘法策略。远途费和半日租金属于固定计算+乘法运算的综合策略。起步价会根据不同车型计算不同费用的价格组计算策略。在价格计算过程中,接口PricingStrategy定义价格计算的策略,代码如下:
public interface PricingStrategy {
/**
* 计算价格
* @param pricingStrategy 计价策略
* @param priceBo 价格配置
* @param orderPriceDto 计价订单
* @return
*/
BigDecimal pricing(PricingStrategyEnum pricingStrategy, PriceBo priceBo, OrderPriceDto orderPriceDto);
}
接口PricingStrategy计算策略的实现子类代码如下:
FixedStrategy,固定金额计算策略。
MultiplyStrategy,乘法计算策略。
FixedOrMultiplyStrategy,固定值+乘法计算策略。
PriceGroupStrategy,价格组计算策略。
PricingStrategyContext,价格计算策略上下文。
MultiplyStrategy策略,基于金额amount与计价数量number的乘积计算价格,代码如下:
public class MultiplyStrategy implements PricingStrategy {
@Override
public BigDecimal pricing(PricingStrategyEnum pricingStrategy, PriceBo priceBo, OrderPriceDto orderPriceDto) {
BigDecimal amount;
Map<String, BigDecimal> numberMap = NumberSelectorManager.select(priceBo, orderPriceDto);
if (Objects.isNull(amount = priceBo.getAmount()) || MapUtils.isEmpty(numberMap)) {
log.warn("amount or number is empty!price [{}],orderPriceDto [{}]",
JSON.toJSONString(priceBo), JSON.toJSONString(orderPriceDto));
return null;
}
// 单价乘于数量
BigDecimal number;
if (NumberUtil.isLessOrEqual(amount, BigDecimal.ZERO)
|| Objects.isNull(number = numberMap.get(priceBo.getCode()))
|| NumberUtil.isLessOrEqual(number, BigDecimal.ZERO)) {
return null;
}
return NumberUtil.mul(amount, number);
}
}
PricingStrategyContext,价格计算策略上下文,根据计价类型动态选择计算策略,并缓存了所有的计价策略,代码如下:
public class PricingStrategyContext {
private final Map<PricingStrategyEnum, PricingStrategy> pricingModeMap;
private PricingStrategyContext() {
pricingModeMap = ImmutableMap.of(
PricingStrategyEnum.FIXED_OR_MULTIPLYING, new FixedOrMultiplyStrategy(),
PricingStrategyEnum.MULTIPLYING, new MultiplyStrategy(),
PricingStrategyEnum.FIXED, new FixedStrategy(),
PricingStrategyEnum.PRICE_GROUP, new PriceGroupStrategy()
);
}
/**
* 计算价格
*
* @param price 价格配置
* @param orderPriceDto 计价订单
* @return
*/
public BigDecimal pricing(PriceBo price, OrderPriceDto orderPriceDto) {
Optional<PricingStrategyEnum> pricingTypeEnumOptional;
PricingStrategy pricingStrategy;
if (Objects.isNull(price)
|| Objects.isNull(pricingTypeEnumOptional = PricingStrategyEnum.valueOf(price.getPricingStrategy()))
|| !pricingTypeEnumOptional.isPresent()
|| Objects.isNull(pricingStrategy = PricingStrategyManagerInstance.INSTANCE.pricingModeMap.get(pricingTypeEnumOptional.get()))) {
log.warn("no matched pricing mode!price [{}],orderPriceDto [{}]", JSON.toJSONString(price), JSON.toJSONString(orderPriceDto));
return null;
}
return pricingStrategy.pricing(pricingTypeEnumOptional.get(), price, orderPriceDto);
}
/**
* 单例模式获取PricingModeManager
*/
public static PricingStrategyContext getInstance() {
return PricingStrategyManagerInstance.INSTANCE;
}
private static final class PricingStrategyManagerInstance {
private static final PricingStrategyContext INSTANCE = new PricingStrategyContext();
}
}