一個spring-boot自動注入策略工廠的starter (設計模式:策略模式 工廠模式 單例模式)
這個專案寫了幾天了 想寫個博客記錄一下 這個心路歷程 也是和大家的一份分享 但是比較懶 一直沒寫 今天是2020年12月31日 2020年的最后一天了 這一年發生了一些眾所周知的事情 想到這些事 我提起筆想記錄一下
代碼鏈接
專案需求
最近在做 資料可視化 的專案 有一些excel匯入的結構化資料. 雖然資料比較完整的 有一部分是從其他系統中匯出的資料 但是也有一部分是手填的資料 還是需要做一下資料審計的 把 缺失值 例外值 偏離值 找出來
- 缺失值 : NULL NONE NaN 空格 空字符
- 例外值 : 0值 負值 小于1的數
- 離群值: 箱線圖模型超過上界下界的值

簡單技術實作
遍歷資料庫表的欄位 查找 缺失值 例外值 加入串列 再把串列合并成了 例外值 的串列
for(String table : tableList){
for(String field : fieldList){
// 資料庫中查詢到的資料
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","負值");
negativeArr.add(data);
}else if(smallIndexlist.size()>0){
data.put("index_list", month);
data.put("type","小數");
smallArr.add(data);
}
}
allArr.addAll(nullArr);
allArr.addAll(zeroArr);
allArr.addAll(negativeArr);
allArr.addAll(smallArr);
}
}
這是一個簡單的實作了 可以滿足我們的要求 但是問題來了 我們是通過嵌套 if else 的方式 來獲取資料的 當我們的表和欄位發生了改變我們再來 修改資料是很麻煩的 這不符合 開閉原則(對擴展開放,對修改關閉) 代碼也不優雅 會影響我們對代碼的復用以及后續的維護
那么我們需要對代碼進行重構
代碼重構-使用策略模式
這段代碼中 我們需要對不同表的指定幾個欄位進行處理 也需要對不同的例外值型別進行處理 那么我們可以
- 將表定義為一個策略
- 將例外值型別定義為一個策略
表的策略中包括了需要處理的欄位 然后欄位需要處理的例外值型別通過表策略定義
策略的實作需要繼承自策略介面 這樣我們再利用 spring-boot 的Map注入 將所有的策略實作注入到一個Map中 我們可以根據名稱直接get
表策略介面
需要兩個方法 一個是獲取全部欄位的方法 一個是獲取指定欄位的資料
public interface IAuditStrategy {
List<String> listField();
List<Map> listData(String field);
}
四個表策略實作
@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) {
...
}
}
例外值策略介面
可以設定例外型別 放入值 生成索引串列 值串列
資料結構: List< Map< String, Object > >
[
{
type: '空值',
indexList: [ 0 , 1 , 2 ],
...
}
]
public interface IAuditInvalidStrategy<T> extends Strategy {
/**
* @param type 例外值型別
*/
void setType(String type);
/**
* @return 例外值型別
*/
String getType();
/**
* 手動設定值串列
*
* @param valueList 值串列
*/
void setValueList(List<T> valueList);
/**
* 添加值
*
* @param value 值
*/
void addValue(T value);
/**
* 添加索引 需要維護一個索引串列
*
* @param index 索引
* @param value 值
*/
void addIndex(Integer index, T value);
/**
* 獲取添加的索引串列
*
* @return 索引串列
*/
List<Integer> getIndexList();
/**
* 添加例外值 map 添加后會清空索引串列 值串列
*
* @param map map
*/
void add(Map map);
/**
* 獲取全部的map 獲取后會清空 list
*
* @return 全部map
*/
List<Map> getList();
/**
* @return list是否為空
*/
boolean isEmpty();
/**
* @return list是否不為空
*/
boolean isNotEmpty();
}
例外值策略抽象類
抽象類是主要的對資料結構的實作 是策略核心方法的實作 例外值策略實作需要繼承這個抽象類 定義了索引串列和值串列 以及全部的串列
簡化了一些實作 文章里只展示業務邏輯
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) {
// 例外值判斷簡化了實作 這里只展示業務邏輯
return Objects.isNull(value);
}
protected boolean isZero(T value) {
// 例外值判斷簡化了實作 這里只展示業務邏輯
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;
}
}
例外值策略實作
主要的實作在抽象類里面已經實作了 不同的策略只需要實作 addIndex 方法 如果是當前例外型別就把索引加入索引串列
@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();
}
}
策略模式重構后的代碼變得優雅了將實作與主業務邏輯解耦 如果需要再加入表欄位 或者例外值處理型別 只需要創建對應的檔案 實作策略介面 使用 @Component 注解 交由spring-boot管理 spring-boot 會自動注入到策略Map 我們只需要提供一個字串就可以獲取對應的策略 無需if else判斷
成員變數 執行緒安全問題
spring-boot 中的 bean 是單例的 一個 bean 的成員變數會被多個執行緒訪問 我們的例外值策略實作中的 indexlist 和 list 并發訪問會出現 執行緒安全 的問題 這個時候我們可以引入一個策略工廠 strategyFatctory
public abstract class AbsInvalidStrategy<T> implements IAuditInvalidStrategy<T> {
protected List<T> valueList;
protected List<Integer> indexList;
private List<Map> list;
}
spring-boot-starter 策略工廠
通過 spring-boot-starter 注入一個 策略工廠 每個執行緒從工廠中創建map避免共享成員變數導致的 執行緒安全 問題
1.策略注解
策略注解 結合了 @Component 會將策略注入到 spring-boot 中 可以通過默認的map方式注入 也可以通過 策略工廠 生產
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface StrategyComponent {
String value();
}
使用注解
@StrategyComponent("auditStrategy_one")
public class OneAuditStrategyImpl implements IAuditStrategy {
...
}
2.策略介面
策略介面只做為一個標識 沒有任何的方法
public interface Strategy {
}
表策略和例外值策略介面繼承策略介面
public interface IAuditStrategy extends Strategy {
...
}
public interface IAuditInvalidStrategy<T> extends Strategy {
...
}
3.策略工廠
public class StrategyFactory {
// 策略工廠實體單例
private static volatile StrategyFactory instance = null;
// 策略介面Map<策略介面包名,Map<策略StrategyComponent名,策略實作類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;
}
/**
* 根據策略介面獲取實作自該介面的所有策略實作
*
* @param strategyInterfaceClass 策略介面
* @param <T> 策略介面型別
* @return 回傳實作自該介面的所有策略實作的物件實體
*/
public <T> Map<String, T> getStrategyMap(Class<? extends T> strategyInterfaceClass) {
Map<String, T> strategyMap = new HashMap<>();
// 從策略介面Map中獲取實作自該介面的map
Map<String, Class> strategyClassMap = interfaceStrategyMap.get(strategyInterfaceClass.getName());
// 遍歷map獲取class檔案生成策略物件實體
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;
}
}
策略工廠使用 通過
@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<>();
// 獲取實作自策略介面的所有strategyComponent bean
Map<String, Strategy> strategyMap = applicationContext.getBeansOfType(Strategy.class);
for (Map.Entry<String, Strategy> strategyEntry : strategyMap.entrySet()) {
// 策略實作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;
}
/**
* 通過策略實作class 反射 獲取實作的全部策略介面名稱
*
* @param strategyClass
* @return
*/
private List<String> getInterfaceNameList(Class strategyClass) {
List<String> interfaceNameList = new ArrayList<>();
// 從遞回全部父類中找到實作的介面
getExtendsOf(strategyClass, interfaceNameList);
return interfaceNameList;
}
/**
* 從遞回全部父類中找到實作的介面
*
* @param strategyClass 當前類
* @param interfaceNameList 介面名稱串列
*/
public void getExtendsOf(Class strategyClass, List<String> interfaceNameList) {
// 獲取父類
Class supperClass = strategyClass.getSuperclass();
if (Objects.nonNull(supperClass)) {
// 如果存在父類 遞回呼叫
getExtendsOf(supperClass, interfaceNameList);
}
// 獲取實作的介面陣列
Class<?>[] interfaces = strategyClass.getInterfaces();
if (ArrayUtils.isNotEmpty(interfaces)) {
// 獲取繼承自Strategy介面的策略介面
getImplementsOf(strategyClass, interfaceNameList);
}
}
/**
* 遞回查找繼承自Strategy介面的策略介面
*
* @param strategyClass 實作了策略介面的策略類
* @param interfaceNameList 策略介面名稱串列
* @return 回傳是否為Strategy
*/
public boolean getImplementsOf(Class strategyClass, List<String> interfaceNameList) {
// 獲取策略介面中的繼承或者多繼承的介面陣列
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
我們需要寫一個 spring-boot-starter 在pom中引入這個starter 就會自動加載這個 策略工廠
org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.colagy.starter.strategy.StrategyConfiguration
代碼連接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/244794.html
標籤:其他
