使用策略設計模式+工廠模式+模板方法模式取代if else
阿新 • • 發佈:2022-03-16
關鍵點: InitializingBean和它的afterPropertiesSet()方法,抽象類
效果測試類
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 22:23
*/
關鍵程式碼
抽象類
/**
* @author : lyn
* 技術點 :模板方法設計模式
* 可處理對於多種不同的返回邏輯
* @date : 2022/3/15 21:48
*/
public abstract class AbstractHandler implements InitializingBean {
public void methodA(){
//對於未重寫的,丟擲不支援操作異常
throw new UnsupportedOperationException();
}
public String methodB(){
throw new UnsupportedOperationException();
}
}
兩個實現
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:55
*/
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:58
*/
工廠類
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:59
*/
public class HandlerFactory {
private static Map<String, AbstractHandler> strategyMap = new HashMap<>();
public static AbstractHandler getInvokeStrategy(String str) {
return strategyMap.get(str);
}
public static void register(String str, AbstractHandler handler) {
if (StringUtils.isEmpty(str) || handler == null){
return;
}
strategyMap.put(str, handler);
}
}