策略管理类

//定义策略接口
public interface Strategy<T> {

/**
* 策略标识
*
* @return
*/
T strategy();

}

// 定义策略管理器
package com.serviceshare.springboot.strategy;

import com.serviceshare.springboot.SpringContextInitialize;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* 策略对象管理器
*/
public class StrategyManager {

private static final Map<Class<?>, Map<String, Object>> TYPE_CACHE = new HashMap<>();
private static final Map<Class<? extends Strategy>, Map<String, Object>> TYPE_Strategy_CACHE = new HashMap<>();

public static <T> T byName(Class<T> interfaceZ, String name) {
Map<String, Object> cacheMap = Optional.ofNullable(TYPE_CACHE.get(interfaceZ)).orElse(new HashMap<>());
final Object cacheBean = cacheMap.get(name);
if (cacheBean != null) {
return (T) cacheBean;
}
TYPE_CACHE.putIfAbsent(interfaceZ, cacheMap);
final Object bean = SpringContextInitialize.context.getBean(name, interfaceZ);
cacheMap.put(name, bean);
return (T) bean;
}

public static <T> T byStrategy(Class<? extends Strategy> iStrategyClass, String Strategy) {
Map<String, Object> cacheMap = Optional.ofNullable(TYPE_Strategy_CACHE.get(iStrategyClass)).orElse(new HashMap<>());
final Object cacheBean = cacheMap.get(Strategy);
if (cacheBean != null) {
return (T) cacheBean;
}

TYPE_Strategy_CACHE.putIfAbsent(iStrategyClass, cacheMap);
final Map<String, ? extends Strategy> beans = SpringContextInitialize.context.getBeansOfType(iStrategyClass);
Strategy bean = null;
for (Strategy beanX : beans.values()) {
if (Strategy.equals(beanX.strategy().toString())) {
bean = beanX;
break;
}
}
cacheMap.put(Strategy, bean);
return (T) bean;
}


}


//使用
BankPayService bankPayService = StrategyManager.byStrategy(BankPayService.class, productSubTypeEnum.toString());
PaymentTransQueryDTO paymentTransQueryDTO = bankPayService.payQuery(orderFlow);
posted @ 2024-02-27 17:28  静候。  阅读(3)  评论(0编辑  收藏  举报