一個(gè)spring-boot自動(dòng)注入策略工廠的starter (設(shè)計(jì)模式:策略模式 工廠模式 單例模式)
這個(gè)項(xiàng)目寫(xiě)了幾天了 想寫(xiě)個(gè)博客記錄一下 這個(gè)心路歷程 也是和大家的一份分享 但是比較懶 一直沒(méi)寫(xiě) 今天是2020年12月31日 2020年的最后一天了 這一年發(fā)生了一些眾所周知的事情 想到這些事 我提起筆想記錄一下
代碼鏈接
項(xiàng)目需求
最近在做 數(shù)據(jù)可視化
的項(xiàng)目 有一些excel導(dǎo)入的結(jié)構(gòu)化數(shù)據(jù). 雖然數(shù)據(jù)比較完整的 有一部分是從其他系統(tǒng)中導(dǎo)出的數(shù)據(jù) 但是也有一部分是手填的數(shù)據(jù) 還是需要做一下數(shù)據(jù)審計(jì)的 把 缺失值
異常值
偏離值
找出來(lái)
- 缺失值 : NULL NONE NaN 空格 空字符
- 異常值 : 0值 負(fù)值 小于1的數(shù)
- 離群值: 箱線圖模型超過(guò)上界下界的值
簡(jiǎn)單技術(shù)實(shí)現(xiàn)
遍歷數(shù)據(jù)庫(kù)表的字段 查找 缺失值
異常值
加入列表 再把列表合并成了 異常值
的列表
for(String table : tableList){
for(String field : fieldList){
// 數(shù)據(jù)庫(kù)中查詢到的數(shù)據(jù)
List<Map> dataList = new ArrayList();
// a/b/c/d表 a/b/c/d字段
if("a".equals(table)){
if("a".equals(field)){
dataList = aDao.listFieldA();
} else if("b".equals(field)){
dataList = aDao.listFieldB();
} else if("c".equals(field)){
dataList = aDao.listFieldC();
} else if("d".equals(field)){
dataList = aDao.listFieldD();
}
} else if("b".equals(table)){
if("a".equals(field)){
dataList = bDao.listFieldA();
}
} else if("c".equals(table)){
if("a".equals(field)){
dataList = cDao.listFieldA();
} else if("b".equals(field)){
dataList = cDao.listFieldB();
} else if("c".equals(field)){
dataList = cDao.listFieldC();
}
} else if("d".equals(table)){
if("a".equals(field)){
dataList = dDao.listFieldA();
} else if("b".equals(field)){
dataList = dDao.listFieldB();
} else if("c".equals(field)){
dataList = dDao.listFieldC();
} else if("d".equals(field)){
dataList = dDao.listFieldD();
}
}
if(Collections.isEmpty(dataList)){
return;
}
JSONArray nullArr=new JSONArray();
JSONArray zeroArr=new JSONArray();
JSONArray negativeArr=new JSONArray();
JSONArray smallArr=new JSONArray();
// 全部異常值
JSONArray allArr=new JSONArray();
for (Map<String,Object> map : totalPowerAllMonth) {
String electricity_consumption_str_list = (String) map.get("electricity_consumption_list");
String[] list = StringUtils.split(electricity_consumption_str_list, ',');
if (Objects.isNull(list)) {
continue;
}
JSONObject data;
data = new JSONObject();
List<Integer> nullIndexList=new ArrayList();
List<Integer> zeroIndexList=new ArrayList();
List<Integer> negativeIndexList=new ArrayList();
List<Integer> smallIndexList=new ArrayList();
int month = 0;
for (String electricity_consumption_str : list) {
month++;
Double current = null;
try {
current = Double.valueOf(electricity_consumption_str);
} catch (Exception e) {
nullIndexList.add(month);
continue;
}
if (Objects.isNull(current)) {
nullIndexList.add(month);
}else if("0".equals(current.toString())){
zeroIndexList.add(month);
}else if(current<0){
negativeIndexList.add(month);
}else if(current<1){
smallIndexList.add(month);
}
}
data.put("electricity_consumption", pre.toString());
data.put("province", map.get("province"));
data.put("data_year", map.get("data_year"));
data.put("kpi_num", map.get("kpi_num"));
if(nullIndexlist.size()>0){
data.put("index_list", month);
data.put("type","空值");
nullArr.add(data);
}else if(zeroIndexlist.size()>0){
data.put("index_list", month);
data.put("type","零值");
zeroArr.add(data);
}else if(negativeIndexlist.size()>0){
data.put("index_list", month);
data.put("type","負(fù)值");
negativeArr.add(data);
}else if(smallIndexlist.size()>0){
data.put("index_list", month);
data.put("type","小數(shù)");
smallArr.add(data);
}
}
allArr.addAll(nullArr);
allArr.addAll(zeroArr);
allArr.addAll(negativeArr);
allArr.addAll(smallArr);
}
}
這是一個(gè)簡(jiǎn)單的實(shí)現(xiàn)了 可以滿足我們的要求 但是問(wèn)題來(lái)了 我們是通過(guò)嵌套 if else 的方式 來(lái)獲取數(shù)據(jù)的 當(dāng)我們的表和字段發(fā)生了改變我們?cè)賮?lái) 修改數(shù)據(jù)是很麻煩的 這不符合 開(kāi)閉原則(對(duì)擴(kuò)展開(kāi)放,對(duì)修改關(guān)閉)
代碼也不優(yōu)雅 會(huì)影響我們對(duì)代碼的復(fù)用以及后續(xù)的維護(hù)
那么我們需要對(duì)代碼進(jìn)行重構(gòu)
代碼重構(gòu)-使用策略模式
這段代碼中 我們需要對(duì)不同表的指定幾個(gè)字段進(jìn)行處理 也需要對(duì)不同的異常值類型進(jìn)行處理 那么我們可以
- 將表定義為一個(gè)策略
- 將異常值類型定義為一個(gè)策略
表的策略中包括了需要處理的字段 然后字段需要處理的異常值類型通過(guò)表策略定義
策略的實(shí)現(xiàn)需要繼承自策略接口 這樣我們?cè)倮?spring-boot
的Map注入 將所有的策略實(shí)現(xiàn)注入到一個(gè)Map中 我們可以根據(jù)名稱直接get
表策略接口
需要兩個(gè)方法 一個(gè)是獲取全部字段的方法 一個(gè)是獲取指定字段的數(shù)據(jù)
public interface IAuditStrategy {
List<String> listField();
List<Map> listData(String field);
}
四個(gè)表策略實(shí)現(xiàn)
@Component("auditStrategy_one")
public class OneAuditStrategyImpl implements IAuditStrategy {
@Autowired
private Dao dao;
@Override
public List<String> listField() {
List<String> fieldList = new ArrayList<>();
fieldList.add("a");
fieldList.add("b");
fieldList.add("c");
fieldList.add("d");
return fieldList;
}
@Override
public List<Map> listData(String field) {
switch (field) {
case "a":
return dao.listA();
case "b":
return dao.listB();
case "c":
return dao.listC();
case "d":
return dao.listD();
}
return null;
}
}
@Component("auditStrategy_two")
public class TwoAuditStrategyImpl implements IAuditStrategy {
@Override
public List<String> listField() {
...
}
@Override
public List<Map> listData(String field) {
...
}
}
@Component("auditStrategy_three")
public class ThreeAuditStrategyImpl implements IAuditStrategy {
@Override
public List<String> listField() {
...
}
@Override
public List<Map> listData(String field) {
...
}
}
@Component("auditStrategy_four")
public class FourAuditStrategyImpl implements IAuditStrategy {
@Override
public List<String> listField() {
...
}
@Override
public List<Map> listData(String field) {
...
}
}
異常值策略接口
可以設(shè)置異常類型 放入值 生成索引列表 值列表
數(shù)據(jù)結(jié)構(gòu): List< Map< String, Object > >
[
{
type: '空值',
indexList: [ 0 , 1 , 2 ],
...
}
]
public interface IAuditInvalidStrategy<T> extends Strategy {
/**
* @param type 異常值類型
*/
void setType(String type);
/**
* @return 異常值類型
*/
String getType();
/**
* 手動(dòng)設(shè)置值列表
*
* @param valueList 值列表
*/
void setValueList(List<T> valueList);
/**
* 添加值
*
* @param value 值
*/
void addValue(T value);
/**
* 添加索引 需要維護(hù)一個(gè)索引列表
*
* @param index 索引
* @param value 值
*/
void addIndex(Integer index, T value);
/**
* 獲取添加的索引列表
*
* @return 索引列表
*/
List<Integer> getIndexList();
/**
* 添加異常值 map 添加后會(huì)清空索引列表 值列表
*
* @param map map
*/
void add(Map map);
/**
* 獲取全部的map 獲取后會(huì)清空 list
*
* @return 全部map
*/
List<Map> getList();
/**
* @return list是否為空
*/
boolean isEmpty();
/**
* @return list是否不為空
*/
boolean isNotEmpty();
}
異常值策略抽象類
抽象類是主要的對(duì)數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn) 是策略核心方法的實(shí)現(xiàn) 異常值策略實(shí)現(xiàn)需要繼承這個(gè)抽象類 定義了索引列表和值列表 以及全部的列表
簡(jiǎn)化了一些實(shí)現(xiàn) 文章里只展示業(yè)務(wù)邏輯
public abstract class AbsInvalidStrategy<T> implements IAuditInvalidStrategy<T> {
private String type;
private boolean isIndexEmpty = true;
private boolean isEmpty = true;
protected List<T> valueList;
protected List<Integer> indexList;
private List<Map> list;
protected boolean isNull(T value) {
// 異常值判斷簡(jiǎn)化了實(shí)現(xiàn) 這里只展示業(yè)務(wù)邏輯
return Objects.isNull(value);
}
protected boolean isZero(T value) {
// 異常值判斷簡(jiǎn)化了實(shí)現(xiàn) 這里只展示業(yè)務(wù)邏輯
if (isNull(value)) {
return false;
}
return isZero(value);
}
protected boolean isNegative(T value) {
if (isNull(value) || isZero(value)) {
return false;
}
return isNegative();
}
protected boolean isSmall(T value) {
if (isNull(value) || isZero(value) || isNegative(value)) {
return false;
}
return isSmall();
}
@Override
public void setType(String type) {
this.type = type;
}
@Override
public String getType() {
return type;
}
@Override
public void setValueList(List<T> valueList) {
this.valueList = valueList;
}
@Override
public void addValue(T value) {
if (Objects.isNull(valueList)) {
valueList = new ArrayList<>();
}
valueList.add(value);
}
@Override
public void beforeAddIndex() {
if (Objects.isNull(indexList)) {
indexList = new ArrayList<>();
}
if (isIndexEmpty) {
isIndexEmpty = false;
}
}
@Override
public List<Integer> getIndexList() {
if (Objects.isNull(indexList)) {
indexList = new ArrayList<>();
}
return indexList;
}
@Override
public void add(Map map) {
if (isIndexEmpty) {
indexList = new ArrayList<>();
valueList = new ArrayList<>();
return;
}
if (Objects.isNull(list)) {
list = new ArrayList<>();
}
list.add(map);
if (isEmpty) {
isEmpty = false;
}
indexList = new ArrayList<>();
isIndexEmpty = true;
valueList = new ArrayList<>();
}
@Override
public List<Map> getList() {
isIndexEmpty = true;
indexList = new ArrayList<>();
valueList = new ArrayList<>();
isEmpty = true;
List<Map> ret = Arrays.asList(new Map[list.size()]);
Collections.copy(ret, list);
list = new ArrayList<>();
return ret;
}
@Override
public boolean isEmpty() {
return isEmpty;
}
@Override
public boolean isNotEmpty() {
return !isEmpty;
}
}
異常值策略實(shí)現(xiàn)
主要的實(shí)現(xiàn)在抽象類里面已經(jīng)實(shí)現(xiàn)了 不同的策略只需要實(shí)現(xiàn) addIndex
方法 如果是當(dāng)前異常類型就把索引加入索引列表
@Component("auditStrategyInvalid_零值")
public class AuditZeroStrategyImpl<T> extends AbsInvalidStrategy<T> {
@Override
public void addIndex(Integer index, T value) {
if (isZero(value)) {
beforeAddIndex();
indexList.add(index);
}
}
}
策略注入與使用
@Service
public class AuditService{
@Autowired
private Map<String,IAuditStrategy> auditStrategyMap;
@Autowired
private Map<String,IInvalidStrategy> invalidStrategyMap;
public JSONArray audit(String table,String field,String type){
IAuditStrategy auditStrategy = auditStrategyMap.get("auditStrategy_"+table);
List<Map> dataList = auditStrategy.listData(field);
IInvalidStrategy invalidHandler = invalidStrategyMap.get("auditStrategyInvalid_"+type);
int index=0;
for(Map data:dataList){
List<String> valueList=data.get("valueList");
for(String value_str:valueList){
invalidHandler.addValue(value_str);
invalidHandler.addIndex(index++, value_str);
}
Map invalidMap=new HashMap();
invalidMap.put("dataIndex", invalidHandler.getIndexList());
...
invalidHandler.add(invalidMap);
}
return invalidHandler.getList();
}
}
策略模式重構(gòu)后的代碼變得優(yōu)雅了將實(shí)現(xiàn)與主業(yè)務(wù)邏輯解耦 如果需要再加入表字段 或者異常值處理類型 只需要?jiǎng)?chuàng)建對(duì)應(yīng)的文件 實(shí)現(xiàn)策略接口 使用 @Component
注解 交由spring-boot管理 spring-boot
會(huì)自動(dòng)注入到策略Map 我們只需要提供一個(gè)字符串就可以獲取對(duì)應(yīng)的策略 無(wú)需if else判斷
成員變量 線程安全問(wèn)題
spring-boot
中的 bean
是單例的 一個(gè) bean
的成員變量會(huì)被多個(gè)線程訪問(wèn) 我們的異常值策略實(shí)現(xiàn)中的 indexlist
和 list
并發(fā)訪問(wèn)會(huì)出現(xiàn) 線程安全
的問(wèn)題 這個(gè)時(shí)候我們可以引入一個(gè)策略工廠 strategyFatctory
public abstract class AbsInvalidStrategy<T> implements IAuditInvalidStrategy<T> {
protected List<T> valueList;
protected List<Integer> indexList;
private List<Map> list;
}
spring-boot-starter 策略工廠
通過(guò) spring-boot-starter
注入一個(gè) 策略工廠
每個(gè)線程從工廠中創(chuàng)建map避免共享成員變量導(dǎo)致的 線程安全
問(wèn)題
1.策略注解
策略注解 結(jié)合了 @Component
會(huì)將策略注入到 spring-boot
中 可以通過(guò)默認(rèn)的map方式注入 也可以通過(guò) 策略工廠
生產(chǎn)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface StrategyComponent {
String value();
}
使用注解
@StrategyComponent("auditStrategy_one")
public class OneAuditStrategyImpl implements IAuditStrategy {
...
}
2.策略接口
策略接口只做為一個(gè)標(biāo)識(shí) 沒(méi)有任何的方法
public interface Strategy {
}
表策略和異常值策略接口繼承策略接口
public interface IAuditStrategy extends Strategy {
...
}
public interface IAuditInvalidStrategy<T> extends Strategy {
...
}
3.策略工廠
public class StrategyFactory {
// 策略工廠實(shí)例單例
private static volatile StrategyFactory instance = null;
// 策略接口Map<策略接口包名,Map<策略StrategyComponent名,策略實(shí)現(xiàn)類class>>
protected Map<String, Map<String, Class>> interfaceStrategyMap;
private StrategyFactory() {
}
// 單例模式
static StrategyFactory getInstance() {
if (Objects.isNull(instance)) {
synchronized (StrategyFactory.class) {
if (Objects.isNull(instance)) {
instance = new StrategyFactory();
}
}
}
return instance;
}
void setMap(Map<String, Map<String, Class>> interfaceStrategyMap) {
this.interfaceStrategyMap = interfaceStrategyMap;
}
/**
* 根據(jù)策略接口獲取實(shí)現(xiàn)自該接口的所有策略實(shí)現(xiàn)
*
* @param strategyInterfaceClass 策略接口
* @param <T> 策略接口類型
* @return 返回實(shí)現(xiàn)自該接口的所有策略實(shí)現(xiàn)的對(duì)象實(shí)例
*/
public <T> Map<String, T> getStrategyMap(Class<? extends T> strategyInterfaceClass) {
Map<String, T> strategyMap = new HashMap<>();
// 從策略接口Map中獲取實(shí)現(xiàn)自該接口的map
Map<String, Class> strategyClassMap = interfaceStrategyMap.get(strategyInterfaceClass.getName());
// 遍歷map獲取class文件生成策略對(duì)象實(shí)例
for (Map.Entry<String, Class> entry : strategyClassMap.entrySet()) {
Class strategyClass = entry.getValue();
T strategy = null;
try {
strategy = (T) strategyClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
strategyMap.put(entry.getKey(), strategy);
}
return strategyMap;
}
}
策略工廠使用 通過(guò)
@Service
public class auditService{
@Autowired
private StrategyFactory strategyFactory;
public JSONArray audit(){
// 策略模式
Map<String, IAuditStrategy> auditStrategyMap = strategyFactory.getStrategyMap(IAuditStrategy.class);
}
}
4.配置
@Configuration
public class StrategyConfiguration {
@Autowired
private ApplicationContext applicationContext;
/**
* 策略工廠 bean 生成
*
* @return 策略工廠 bean
*/
@ConditionalOnMissingBean
@Bean
public StrategyFactory getStrategyFactory() {
Map<String, Map<String, Class>> strategyInterfaceMap = new HashMap<>();
// 獲取實(shí)現(xiàn)自策略接口的所有strategyComponent bean
Map<String, Strategy> strategyMap = applicationContext.getBeansOfType(Strategy.class);
for (Map.Entry<String, Strategy> strategyEntry : strategyMap.entrySet()) {
// 策略實(shí)現(xiàn)bean的class
Class strategyClass = strategyEntry.getValue().getClass();
// 策略接口的包名列表
List<String> interfaceNameList = getInterfaceNameList(strategyClass);
if (CollectionUtils.isEmpty(interfaceNameList)) {
continue;
}
// 遍歷策略接口包名生成策略Map
for (String interfaceName : interfaceNameList) {
Map<String, Class> strategyClassMap = strategyInterfaceMap.get(interfaceName);
if (Objects.isNull(strategyClassMap)) {
strategyClassMap = new HashMap<>();
strategyInterfaceMap.put(interfaceName, strategyClassMap);
}
strategyClassMap.put(strategyEntry.getKey(), strategyClass);
}
}
// 策略工廠單例
StrategyFactory strategyFactory = StrategyFactory.getInstance();
// 放入全部的策略
strategyFactory.setMap(strategyInterfaceMap);
return strategyFactory;
}
/**
* 通過(guò)策略實(shí)現(xiàn)class 反射 獲取實(shí)現(xiàn)的全部策略接口名稱
*
* @param strategyClass
* @return
*/
private List<String> getInterfaceNameList(Class strategyClass) {
List<String> interfaceNameList = new ArrayList<>();
// 從遞歸全部父類中找到實(shí)現(xiàn)的接口
getExtendsOf(strategyClass, interfaceNameList);
return interfaceNameList;
}
/**
* 從遞歸全部父類中找到實(shí)現(xiàn)的接口
*
* @param strategyClass 當(dāng)前類
* @param interfaceNameList 接口名稱列表
*/
public void getExtendsOf(Class strategyClass, List<String> interfaceNameList) {
// 獲取父類
Class supperClass = strategyClass.getSuperclass();
if (Objects.nonNull(supperClass)) {
// 如果存在父類 遞歸調(diào)用
getExtendsOf(supperClass, interfaceNameList);
}
// 獲取實(shí)現(xiàn)的接口數(shù)組
Class<?>[] interfaces = strategyClass.getInterfaces();
if (ArrayUtils.isNotEmpty(interfaces)) {
// 獲取繼承自Strategy接口的策略接口
getImplementsOf(strategyClass, interfaceNameList);
}
}
/**
* 遞歸查找繼承自Strategy接口的策略接口
*
* @param strategyClass 實(shí)現(xiàn)了策略接口的策略類
* @param interfaceNameList 策略接口名稱列表
* @return 返回是否為Strategy
*/
public boolean getImplementsOf(Class strategyClass, List<String> interfaceNameList) {
// 獲取策略接口中的繼承或者多繼承的接口數(shù)組
Class[] interfaces = strategyClass.getInterfaces();
if (ArrayUtils.isNotEmpty(interfaces)) {
// 遍歷接口查詢繼承自Strategy的接口
for (Class inter : interfaces) {
// 如果是Strategy返回true
if (Objects.equals(inter.getName(), Strategy.class.getName())) {
return true;
}
// 如果繼承的接口列表中有Strategy 把接口包名加入列表
if (getImplementsOf(inter, interfaceNameList)) {
interfaceNameList.add(inter.getName());
}
}
}
return false;
}
}
spring-boot-starter
我們需要寫(xiě)一個(gè) spring-boot-starter
在pom中引入這個(gè)starter 就會(huì)自動(dòng)加載這個(gè) 策略工廠
org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.colagy.starter.strategy.StrategyConfiguration