背景
平時我們寫業(yè)務(wù)代碼容易遇到一下問題
1、隨著需求的變更添加,代碼變得越來越臃腫,冗余
2、到處都是if else邏輯
3、對外提供很多的入口,對內(nèi)耦合很大,需求添加時經(jīng)常改內(nèi)又改外。但我們都知道,修改源代碼很容易產(chǎn)生新的問題
針對以上問題,我覺得代理模式+反射是比較簡潔的架構(gòu),以下是最佳實踐類圖和代碼

架構(gòu)分析
1、好的架構(gòu),調(diào)用者不需要知道實現(xiàn)細(xì)節(jié),它只管需要給你哪些參數(shù)和返回的數(shù)據(jù)。這里加了一層抽象代理,這一層抽象很重要,使得代碼對外簡單接口,對內(nèi)靈活變化
2、如圖,proxy 調(diào)用2,通過反射技術(shù)省去if else,使得需求添加時,只需繼承IExecutor實現(xiàn),無需修改源碼
最佳實踐代碼
1、對外入口使用一個抽象代理層
/**
* Created jixinshi on 2019-07-04.
* 用于啟動服務(wù)后自動執(zhí)行
*/
@Component
public class DoMain implements CommandLineRunner {
@Resource
private TemplateProxy templateProxy;
@Override
public void run(String... args) {
// 入口
for (ExecutorBeanType type : ExecutorBeanType.values()) {
templateProxy.execute(type.getBean(), type.getDesc());
}
}
}
2、代理層相關(guān)操作(反射技術(shù))
/**
* Created jixinshi on 2019-07-04.
* 代理類
*/
@Component
public class TemplateProxy {
public void execute(String bean, String other){
// TODO 執(zhí)行前操作
doBefore();
TemplateExecutor templateExecutor = (TemplateExecutor) ApplicationHolder.getBean(bean);
templateExecutor.execute(other);
// TODO 執(zhí)行后操作
doAfter();
}
private void doAfter() {
System.out.println("=================== after ===================");
}
private void doBefore() {
System.out.println("=================== before ===================");
}
}
3、具體細(xì)節(jié)實現(xiàn)
/**
* Created jixinshi on 2019-07-04.
*
*/
@Component("firstExecutor")
public class FirstExecutor implements TemplateExecutor{
@Override
public void execute(String other) {
System.out.println("bean [firstExecutor} ==> " + other);
}
}
/**
* Created jixinshi on 2019-07-04.
*/
@Component("secondExecutor")
public class SecondExecutor implements TemplateExecutor{
@Override
public void execute(String other) {
System.out.println("bean [secondExecutor} ==> " + other);
}
}
4、效果圖

代碼地址
https://github.com/RiveLock/test_springboot
總結(jié)
任何復(fù)雜的問題,都可以通過抽象出一層代理來解決,比如
1、nginx反向代理,前端調(diào)用服務(wù)不直接調(diào)用,而是通過nginx代理,這樣抽象出一層代理,這樣使得服務(wù)器對外統(tǒng)一入口和出口,前端無需關(guān)注哪臺服務(wù),并相關(guān)服務(wù)器的細(xì)節(jié)
2、Spring AOP,F(xiàn)eign,中間件,其實都是抽象出一層代理,用于解決復(fù)雜的問題并使得架構(gòu)更加清晰明了
后面我會以代理思維為切入點寫一個系列,敬請期待。。。