Spring中的八大設(shè)計(jì)模式詳解
Spring 框架中運(yùn)用了多種設(shè)計(jì)模式下面為你詳細(xì)介紹 Spring 框架中常見(jiàn)的八大設(shè)計(jì)模式及相關(guān)代碼示例1. 單例模式Singleton Pattern知識(shí)點(diǎn)總結(jié)概念確保一個(gè)類只有一個(gè)實(shí)例并提供一個(gè)全局訪問(wèn)點(diǎn)。在 Spring 中默認(rèn)情況下Bean 的作用域是單例的即整個(gè)應(yīng)用程序中只有一個(gè)實(shí)例。優(yōu)點(diǎn)節(jié)省系統(tǒng)資源減少對(duì)象創(chuàng)建和銷毀的開(kāi)銷。Spring 實(shí)現(xiàn)Spring 容器負(fù)責(zé)管理單例 Bean 的生命周期通過(guò)內(nèi)部的緩存機(jī)制確保一個(gè) Bean 只有一個(gè)實(shí)例。代碼示例importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Scope;// 商品庫(kù)存管理類使用單例模式classProductInventoryManager{privateintstock;publicProductInventoryManager(){this.stock100;}publicintgetStock(){returnstock;}publicvoiddecreaseStock(intquantity){if(stockquantity){stock-quantity;}}}ConfigurationpublicclassAppConfig{BeanScope(singleton)// 默認(rèn)就是單例可省略publicProductInventoryManagerproductInventoryManager(){returnnewProductInventoryManager();}}2. 工廠模式Factory Pattern知識(shí)點(diǎn)總結(jié)概念定義一個(gè)創(chuàng)建對(duì)象的接口讓子類決定實(shí)例化哪個(gè)類。Spring 中的BeanFactory和ApplicationContext就是工廠模式的典型應(yīng)用它們負(fù)責(zé)創(chuàng)建和管理 Bean 對(duì)象。優(yōu)點(diǎn)將對(duì)象的創(chuàng)建和使用分離提高代碼的可維護(hù)性和可擴(kuò)展性。Spring 實(shí)現(xiàn)通過(guò)配置文件或注解定義 Bean 的創(chuàng)建方式Spring 容器根據(jù)這些配置創(chuàng)建 Bean 實(shí)例。代碼示例importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;// 商品服務(wù)接口interfaceProductService{StringgetProductInfo();}// 具體商品服務(wù)實(shí)現(xiàn)類classElectronicsProductServiceimplementsProductService{OverridepublicStringgetProductInfo(){returnThis is an electronics product.;}}classClothingProductServiceimplementsProductService{OverridepublicStringgetProductInfo(){returnThis is a clothing product.;}}// 商品服務(wù)工廠類classProductServiceFactory{publicstaticProductServicecreateProductService(Stringtype){if(electronics.equals(type)){returnnewElectronicsProductService();}elseif(clothing.equals(type)){returnnewClothingProductService();}returnnull;}}ConfigurationpublicclassAppConfig{BeanpublicProductServiceelectronicsProductService(){returnProductServiceFactory.createProductService(electronics);}BeanpublicProductServiceclothingProductService(){returnProductServiceFactory.createProductService(clothing);}}3. 代理模式Proxy Pattern知識(shí)點(diǎn)總結(jié)概念為其他對(duì)象提供一種代理以控制對(duì)這個(gè)對(duì)象的訪問(wèn)。Spring AOP面向切面編程就是基于代理模式實(shí)現(xiàn)的通過(guò)代理對(duì)象在目標(biāo)對(duì)象的方法前后添加額外的邏輯如日志記錄、事務(wù)管理等。優(yōu)點(diǎn)可以在不修改目標(biāo)對(duì)象代碼的情況下增強(qiáng)其功能。Spring 實(shí)現(xiàn)Spring AOP 支持兩種代理方式JDK 動(dòng)態(tài)代理基于接口和 CGLIB 代理基于類。代碼示例importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.After;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Before;importorg.aspectj.lang.annotation.Pointcut;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.EnableAspectJAutoProxy;// 商品服務(wù)接口interfaceProductService{voidsellProduct(StringproductId);}// 具體商品服務(wù)實(shí)現(xiàn)類classProductServiceImplimplementsProductService{OverridepublicvoidsellProduct(StringproductId){System.out.println(Selling product: productId);}}// 切面類AspectComponentclassProductServiceAspect{Pointcut(execution(* com.example.ProductService.sellProduct(..)))publicvoidsellProductPointcut(){}Before(sellProductPointcut())publicvoidbeforeSellProduct(JoinPointjoinPoint){System.out.println(Before selling product: joinPoint.getArgs()[0]);}After(sellProductPointcut())publicvoidafterSellProduct(JoinPointjoinPoint){System.out.println(After selling product: joinPoint.getArgs()[0]);}}ConfigurationEnableAspectJAutoProxyComponentScan(basePackagescom.example)publicclassAppConfig{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontextnewAnnotationConfigApplicationContext(AppConfig.class);ProductServiceproductServicecontext.getBean(ProductService.class);productService.sellProduct(P001);context.close();}}4. 適配器模式Adapter Pattern知識(shí)點(diǎn)總結(jié)概念將一個(gè)類的接口轉(zhuǎn)換成客戶希望的另外一個(gè)接口。Spring 中的HandlerAdapter就是適配器模式的應(yīng)用它將不同類型的處理器適配成統(tǒng)一的處理方式。優(yōu)點(diǎn)使原本由于接口不兼容而不能一起工作的那些類可以一起工作。Spring 實(shí)現(xiàn)通過(guò)實(shí)現(xiàn)不同的HandlerAdapter來(lái)適配不同類型的處理器。代碼示例// 舊的商品服務(wù)接口interfaceOldProductService{voidoldSellProduct(StringproductId);}// 舊的商品服務(wù)實(shí)現(xiàn)類classOldProductServiceImplimplementsOldProductService{OverridepublicvoidoldSellProduct(StringproductId){System.out.println(Old way of selling product: productId);}}// 新的商品服務(wù)接口interfaceNewProductService{voidnewSellProduct(StringproductId);}// 適配器類classProductServiceAdapterimplementsNewProductService{privateOldProductServiceoldProductService;publicProductServiceAdapter(OldProductServiceoldProductService){this.oldProductServiceoldProductService;}OverridepublicvoidnewSellProduct(StringproductId){oldProductService.oldSellProduct(productId);}}5. 裝飾器模式Decorator Pattern知識(shí)點(diǎn)總結(jié)概念動(dòng)態(tài)地給一個(gè)對(duì)象添加一些額外的職責(zé)。Spring 中的TransactionAwareCacheDecorator就是裝飾器模式的應(yīng)用它在緩存對(duì)象的基礎(chǔ)上添加了事務(wù)管理的功能。優(yōu)點(diǎn)比繼承更靈活可以在運(yùn)行時(shí)動(dòng)態(tài)地添加或刪除功能。Spring 實(shí)現(xiàn)通過(guò)創(chuàng)建裝飾器類包裝目標(biāo)對(duì)象并添加額外的功能。代碼示例// 商品服務(wù)接口interfaceProductService{StringgetProductInfo();}// 具體商品服務(wù)實(shí)現(xiàn)類classBasicProductServiceimplementsProductService{OverridepublicStringgetProductInfo(){returnBasic product information.;}}// 裝飾器抽象類abstractclassProductServiceDecoratorimplementsProductService{protectedProductServiceproductService;publicProductServiceDecorator(ProductServiceproductService){this.productServiceproductService;}}// 具體裝飾器類添加額外信息classPremiumProductServiceDecoratorextendsProductServiceDecorator{publicPremiumProductServiceDecorator(ProductServiceproductService){super(productService);}OverridepublicStringgetProductInfo(){returnproductService.getProductInfo() - Premium features included.;}}6. 觀察者模式Observer Pattern知識(shí)點(diǎn)總結(jié)概念定義對(duì)象間的一種一對(duì)多的依賴關(guān)系當(dāng)一個(gè)對(duì)象的狀態(tài)發(fā)生改變時(shí)所有依賴它的對(duì)象都會(huì)得到通知并自動(dòng)更新。Spring 中的事件機(jī)制就是基于觀察者模式實(shí)現(xiàn)的如ApplicationEvent和ApplicationListener。優(yōu)點(diǎn)實(shí)現(xiàn)了對(duì)象之間的解耦提高了系統(tǒng)的可維護(hù)性和可擴(kuò)展性。Spring 實(shí)現(xiàn)通過(guò)定義事件類和監(jiān)聽(tīng)器類當(dāng)事件發(fā)布時(shí)監(jiān)聽(tīng)器會(huì)接收到通知并執(zhí)行相應(yīng)的操作。代碼示例importorg.springframework.context.ApplicationEvent;importorg.springframework.context.ApplicationListener;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importorg.springframework.context.annotation.Configuration;// 訂單創(chuàng)建事件類classOrderCreatedEventextendsApplicationEvent{privateStringorderId;publicOrderCreatedEvent(Objectsource,StringorderId){super(source);this.orderIdorderId;}publicStringgetOrderId(){returnorderId;}}// 訂單創(chuàng)建事件監(jiān)聽(tīng)器類classOrderCreatedEventListenerimplementsApplicationListenerOrderCreatedEvent{OverridepublicvoidonApplicationEvent(OrderCreatedEventevent){System.out.println(Order created: event.getOrderId());}}// 訂單服務(wù)類發(fā)布訂單創(chuàng)建事件classOrderService{privateAnnotationConfigApplicationContextcontext;publicOrderService(AnnotationConfigApplicationContextcontext){this.contextcontext;}publicvoidcreateOrder(StringorderId){OrderCreatedEventeventnewOrderCreatedEvent(this,orderId);context.publishEvent(event);}}ConfigurationpublicclassAppConfig{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontextnewAnnotationConfigApplicationContext(AppConfig.class);OrderServiceorderServicenewOrderService(context);orderService.createOrder(O001);context.close();}}7. 策略模式Strategy Pattern知識(shí)點(diǎn)總結(jié)概念定義一系列的算法把它們一個(gè)個(gè)封裝起來(lái)并且使它們可以相互替換。Spring 中的ResourceLoader就是策略模式的應(yīng)用根據(jù)不同的資源類型選擇不同的加載策略。優(yōu)點(diǎn)可以在運(yùn)行時(shí)動(dòng)態(tài)地選擇不同的算法提高了系統(tǒng)的靈活性。Spring 實(shí)現(xiàn)通過(guò)定義策略接口和具體的策略實(shí)現(xiàn)類根據(jù)不同的需求選擇不同的策略。代碼示例// 支付策略接口interfacePaymentStrategy{voidpay(doubleamount);}// 具體支付策略實(shí)現(xiàn)類 - 支付寶支付classAlipayPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Alipay.);}}// 具體支付策略實(shí)現(xiàn)類 - 微信支付classWechatPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Wechat Pay.);}}// 訂單服務(wù)類根據(jù)不同的支付策略進(jìn)行支付classOrderService{privatePaymentStrategypaymentStrategy;publicOrderService(PaymentStrategypaymentStrategy){this.paymentStrategypaymentStrategy;}publicvoidprocessOrder(doubleamount){paymentStrategy.pay(amount);}}8. 模板方法模式Template Method Pattern知識(shí)點(diǎn)總結(jié)概念定義一個(gè)操作中的算法的骨架而將一些步驟延遲到子類中。Spring 中的JdbcTemplate就是模板方法模式的應(yīng)用它定義了 JDBC 操作的基本步驟如獲取連接、執(zhí)行 SQL 語(yǔ)句、關(guān)閉連接等具體的 SQL 語(yǔ)句由子類實(shí)現(xiàn)。優(yōu)點(diǎn)提高了代碼的復(fù)用性避免了代碼的重復(fù)編寫(xiě)。Spring 實(shí)現(xiàn)通過(guò)定義抽象類和具體的模板方法子類繼承抽象類并實(shí)現(xiàn)具體的步驟。代碼示例importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.jdbc.datasource.DriverManagerDataSource;// 抽象的商品數(shù)據(jù)訪問(wèn)類abstractclassAbstractProductDao{protectedJdbcTemplatejdbcTemplate;publicAbstractProductDao(){DriverManagerDataSourcedataSourcenewDriverManagerDataSource();dataSource.setDriverClassName(com.mysql.jdbc.Driver);dataSource.setUrl(jdbc:mysql://localhost:3306/ecommerce);dataSource.setUsername(root);dataSource.setPassword(password);jdbcTemplatenewJdbcTemplate(dataSource);}// 模板方法定義查詢商品的基本步驟publicfinalStringgetProductInfo(StringproductId){// 執(zhí)行查詢操作StringsqlgetSql();returnjdbcTemplate.queryForObject(sql,String.class,productId);}// 抽象方法由子類實(shí)現(xiàn)具體的 SQL 語(yǔ)句protectedabstractStringgetSql();}// 具體的商品數(shù)據(jù)訪問(wèn)類classProductDaoextendsAbstractProductDao{OverrideprotectedStringgetSql(){returnSELECT product_info FROM products WHERE product_id ?;}}

相關(guān)新聞

2026六盤(pán)水黃金回收白銀回收鉑金回收靠譜臨街實(shí)體公安備案支持到店核驗(yàn)門(mén)店聯(lián)系方式推薦

2026六盤(pán)水黃金回收白銀回收鉑金回收靠譜臨街實(shí)體公安備案支持到店核驗(yàn)門(mén)店聯(lián)系方式推薦

2026六盤(pán)水黃金白銀鉑金回收實(shí)測(cè)榜單|公安備案臨街實(shí)體門(mén)店推薦 六盤(pán)水街頭巷尾貴金屬回收店鋪遍地叢生,行業(yè)套路層出不窮,不少市民變現(xiàn)時(shí)遭遇虛高報(bào)價(jià)、克扣損耗、未經(jīng)同意熔金壓價(jià)等問(wèn)題。為幫助本地居民規(guī)避消費(fèi)陷阱,小編實(shí)地走…

2026/8/1 21:13:20 閱讀更多
2025 年 3 月青少年軟編等考 C 語(yǔ)言四級(jí)真題解析

2025 年 3 月青少年軟編等考 C 語(yǔ)言四級(jí)真題解析

目錄 T1. 兩枚硬幣 思路分析 T2. 完美數(shù)列 思路分析 T3. 多樣解碼 思路分析 T4. 二進(jìn)制串的評(píng)分 思路分析 T1. 兩枚硬幣 題目鏈接:SOJ D1387 伊娃喜歡收集全宇宙的硬幣,包括火星幣等等。一天她到了一家宇宙商店,這家商店可以接受任何星球的貨幣,但有一個(gè)條件,無(wú)論什么價(jià)…

2026/8/1 21:13:20 閱讀更多
新手必看!Princess-connection-farm常見(jiàn)問(wèn)題與腳本報(bào)錯(cuò)解決方法

新手必看!Princess-connection-farm常見(jiàn)問(wèn)題與腳本報(bào)錯(cuò)解決方法

新手必看!Princess-connection-farm常見(jiàn)問(wèn)題與腳本報(bào)錯(cuò)解決方法 【免費(fèi)下載鏈接】Princess-connection-farm 國(guó)服PCR公主連結(jié) 多開(kāi)自動(dòng)農(nóng)場(chǎng)腳本 基于opencvUIAutomator 項(xiàng)目地址: https://gitcode.com/gh_mirrors/pr/Princess-connection-farm Princess-conn…

2026/8/1 22:03:25 閱讀更多
理工科救命[特殊字符]不用學(xué)Origin!論文科研繪圖直接一鍵成片

理工科救命[特殊字符]不用學(xué)Origin!論文科研繪圖直接一鍵成片

誰(shuí)說(shuō)畢設(shè)一定要精通各種繪圖軟件?😭 為了幾張論文圖表,硬啃Origin、Visio、Matlab, 學(xué)一周、調(diào)半天、最后畫(huà)出來(lái)還是被導(dǎo)師吐槽: 配色不學(xué)術(shù)、比例不規(guī)范、標(biāo)注不嚴(yán)謹(jǐn)、風(fēng)格不統(tǒng)一 數(shù)據(jù)做得再好,圖表拉…

2026/8/1 22:03:25 閱讀更多
告別Origin熬夜畫(huà)圖??論文科研繪圖一鍵出高清版圖?

告別Origin熬夜畫(huà)圖??論文科研繪圖一鍵出高清版圖?

誰(shuí)懂理工科、實(shí)證論文的痛😭 論文內(nèi)容寫(xiě)滿了、數(shù)據(jù)全部算完了,最后卡死在科研繪圖! Origin、Matlab零基礎(chǔ)不會(huì)用,自學(xué)教程繁瑣又耗時(shí)間; 自己手畫(huà)圖表粗糙廉價(jià)、配色雜亂、標(biāo)注不規(guī)范; 網(wǎng)上找的圖有水印…

2026/8/1 22:03:25 閱讀更多
如何用云帆在線考試系統(tǒng)快速搭建企業(yè)培訓(xùn)平臺(tái):從零到一完整指南

如何用云帆在線考試系統(tǒng)快速搭建企業(yè)培訓(xùn)平臺(tái):從零到一完整指南

如何用云帆在線考試系統(tǒng)快速搭建企業(yè)培訓(xùn)平臺(tái):從零到一完整指南 【免費(fèi)下載鏈接】yftrain 學(xué)習(xí)系統(tǒng)-在線考試系統(tǒng) 企業(yè)培訓(xùn)內(nèi)訓(xùn)系統(tǒng)-企教培系統(tǒng)平臺(tái)軟件 項(xiàng)目地址: https://gitcode.com/gh_mirrors/yf/yftrain 還在為企業(yè)的員工培訓(xùn)考試煩惱嗎?云…

2026/8/1 21:53:24 閱讀更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O分配PCB板是應(yīng)用材料(Applied Materials)公司生產(chǎn)的一款用于半導(dǎo)體設(shè)備的I/O信號(hào)分配電路板。該型號(hào)(0100-02186)的核心特點(diǎn)如下:專用于Endura等半導(dǎo)體工藝腔室。集成信號(hào)路由與分配功能。連接控制…

2026/8/1 0:09:33 閱讀更多
Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)是日本日清(Nissei)品牌的一款工業(yè)用三相異步電機(jī),適用于自動(dòng)化設(shè)備及通用機(jī)械驅(qū)動(dòng)。該型號(hào)(FFMN-32L-10-T0 40AX)的核心特點(diǎn)如下:三相交流異步電動(dòng)機(jī)。額定…

2026/8/1 0:09:33 閱讀更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O分配PCB板是應(yīng)用材料(Applied Materials)公司生產(chǎn)的一款用于半導(dǎo)體設(shè)備的I/O信號(hào)分配電路板。該型號(hào)(0100-02186)的核心特點(diǎn)如下:專用于Endura等半導(dǎo)體工藝腔室。集成信號(hào)路由與分配功能。連接控制…

2026/8/1 0:09:33 閱讀更多
Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動(dòng)機(jī)是日本日清(Nissei)品牌的一款工業(yè)用三相異步電機(jī),適用于自動(dòng)化設(shè)備及通用機(jī)械驅(qū)動(dòng)。該型號(hào)(FFMN-32L-10-T0 40AX)的核心特點(diǎn)如下:三相交流異步電動(dòng)機(jī)。額定…

2026/8/1 0:09:33 閱讀更多