Spring中的八大設計模式詳解
Spring 框架中運用了多種設計模式下面為你詳細介紹 Spring 框架中常見的八大設計模式及相關代碼示例1. 單例模式Singleton Pattern知識點總結概念確保一個類只有一個實例并提供一個全局訪問點。在 Spring 中默認情況下Bean 的作用域是單例的即整個應用程序中只有一個實例。優(yōu)點節(jié)省系統(tǒng)資源減少對象創(chuàng)建和銷毀的開銷。Spring 實現(xiàn)Spring 容器負責管理單例 Bean 的生命周期通過內(nèi)部的緩存機制確保一個 Bean 只有一個實例。代碼示例importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Scope;// 商品庫存管理類使用單例模式classProductInventoryManager{privateintstock;publicProductInventoryManager(){this.stock100;}publicintgetStock(){returnstock;}publicvoiddecreaseStock(intquantity){if(stockquantity){stock-quantity;}}}ConfigurationpublicclassAppConfig{BeanScope(singleton)// 默認就是單例可省略publicProductInventoryManagerproductInventoryManager(){returnnewProductInventoryManager();}}2. 工廠模式Factory Pattern知識點總結概念定義一個創(chuàng)建對象的接口讓子類決定實例化哪個類。Spring 中的BeanFactory和ApplicationContext就是工廠模式的典型應用它們負責創(chuàng)建和管理 Bean 對象。優(yōu)點將對象的創(chuàng)建和使用分離提高代碼的可維護性和可擴展性。Spring 實現(xiàn)通過配置文件或注解定義 Bean 的創(chuàng)建方式Spring 容器根據(jù)這些配置創(chuàng)建 Bean 實例。代碼示例importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;// 商品服務接口interfaceProductService{StringgetProductInfo();}// 具體商品服務實現(xiàn)類classElectronicsProductServiceimplementsProductService{OverridepublicStringgetProductInfo(){returnThis is an electronics product.;}}classClothingProductServiceimplementsProductService{OverridepublicStringgetProductInfo(){returnThis is a clothing product.;}}// 商品服務工廠類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知識點總結概念為其他對象提供一種代理以控制對這個對象的訪問。Spring AOP面向切面編程就是基于代理模式實現(xiàn)的通過代理對象在目標對象的方法前后添加額外的邏輯如日志記錄、事務管理等。優(yōu)點可以在不修改目標對象代碼的情況下增強其功能。Spring 實現(xiàn)Spring AOP 支持兩種代理方式JDK 動態(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;// 商品服務接口interfaceProductService{voidsellProduct(StringproductId);}// 具體商品服務實現(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知識點總結概念將一個類的接口轉換成客戶希望的另外一個接口。Spring 中的HandlerAdapter就是適配器模式的應用它將不同類型的處理器適配成統(tǒng)一的處理方式。優(yōu)點使原本由于接口不兼容而不能一起工作的那些類可以一起工作。Spring 實現(xiàn)通過實現(xiàn)不同的HandlerAdapter來適配不同類型的處理器。代碼示例// 舊的商品服務接口interfaceOldProductService{voidoldSellProduct(StringproductId);}// 舊的商品服務實現(xiàn)類classOldProductServiceImplimplementsOldProductService{OverridepublicvoidoldSellProduct(StringproductId){System.out.println(Old way of selling product: productId);}}// 新的商品服務接口interfaceNewProductService{voidnewSellProduct(StringproductId);}// 適配器類classProductServiceAdapterimplementsNewProductService{privateOldProductServiceoldProductService;publicProductServiceAdapter(OldProductServiceoldProductService){this.oldProductServiceoldProductService;}OverridepublicvoidnewSellProduct(StringproductId){oldProductService.oldSellProduct(productId);}}5. 裝飾器模式Decorator Pattern知識點總結概念動態(tài)地給一個對象添加一些額外的職責。Spring 中的TransactionAwareCacheDecorator就是裝飾器模式的應用它在緩存對象的基礎上添加了事務管理的功能。優(yōu)點比繼承更靈活可以在運行時動態(tài)地添加或刪除功能。Spring 實現(xiàn)通過創(chuàng)建裝飾器類包裝目標對象并添加額外的功能。代碼示例// 商品服務接口interfaceProductService{StringgetProductInfo();}// 具體商品服務實現(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知識點總結概念定義對象間的一種一對多的依賴關系當一個對象的狀態(tài)發(fā)生改變時所有依賴它的對象都會得到通知并自動更新。Spring 中的事件機制就是基于觀察者模式實現(xiàn)的如ApplicationEvent和ApplicationListener。優(yōu)點實現(xiàn)了對象之間的解耦提高了系統(tǒng)的可維護性和可擴展性。Spring 實現(xiàn)通過定義事件類和監(jiān)聽器類當事件發(fā)布時監(jiān)聽器會接收到通知并執(zhí)行相應的操作。代碼示例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)聽器類classOrderCreatedEventListenerimplementsApplicationListenerOrderCreatedEvent{OverridepublicvoidonApplicationEvent(OrderCreatedEventevent){System.out.println(Order created: event.getOrderId());}}// 訂單服務類發(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知識點總結概念定義一系列的算法把它們一個個封裝起來并且使它們可以相互替換。Spring 中的ResourceLoader就是策略模式的應用根據(jù)不同的資源類型選擇不同的加載策略。優(yōu)點可以在運行時動態(tài)地選擇不同的算法提高了系統(tǒng)的靈活性。Spring 實現(xiàn)通過定義策略接口和具體的策略實現(xiàn)類根據(jù)不同的需求選擇不同的策略。代碼示例// 支付策略接口interfacePaymentStrategy{voidpay(doubleamount);}// 具體支付策略實現(xiàn)類 - 支付寶支付classAlipayPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Alipay.);}}// 具體支付策略實現(xiàn)類 - 微信支付classWechatPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Wechat Pay.);}}// 訂單服務類根據(jù)不同的支付策略進行支付classOrderService{privatePaymentStrategypaymentStrategy;publicOrderService(PaymentStrategypaymentStrategy){this.paymentStrategypaymentStrategy;}publicvoidprocessOrder(doubleamount){paymentStrategy.pay(amount);}}8. 模板方法模式Template Method Pattern知識點總結概念定義一個操作中的算法的骨架而將一些步驟延遲到子類中。Spring 中的JdbcTemplate就是模板方法模式的應用它定義了 JDBC 操作的基本步驟如獲取連接、執(zhí)行 SQL 語句、關閉連接等具體的 SQL 語句由子類實現(xiàn)。優(yōu)點提高了代碼的復用性避免了代碼的重復編寫。Spring 實現(xiàn)通過定義抽象類和具體的模板方法子類繼承抽象類并實現(xiàn)具體的步驟。代碼示例importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.jdbc.datasource.DriverManagerDataSource;// 抽象的商品數(shù)據(jù)訪問類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);}// 抽象方法由子類實現(xiàn)具體的 SQL 語句protectedabstractStringgetSql();}// 具體的商品數(shù)據(jù)訪問類classProductDaoextendsAbstractProductDao{OverrideprotectedStringgetSql(){returnSELECT product_info FROM products WHERE product_id ?;}}

相關新聞

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

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

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

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

2025 年 3 月青少年軟編等考 C 語言四級真題解析

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

2026/8/1 21:13:20 閱讀更多
【計算機畢業(yè)設計單片機案例】基于 STC89C52 的農(nóng)業(yè)土壤濕度實時監(jiān)測裝置設計 基于 51 單片機的小型種植環(huán)境智能管控終端設計(017701)

【計算機畢業(yè)設計單片機案例】基于 STC89C52 的農(nóng)業(yè)土壤濕度實時監(jiān)測裝置設計 基于 51 單片機的小型種植環(huán)境智能管控終端設計(017701)

博主介紹:??碼農(nóng)一枚 ,專注于大學生項目實戰(zhàn)開發(fā)、講解和畢業(yè)🚢文撰寫修改等。全棧領域優(yōu)質創(chuàng)作者,博客之星、掘金/華為云/阿里云/InfoQ等平臺優(yōu)質作者、專注于嵌入式單片機,Java、小程序技術領域和畢業(yè)項目實戰(zhàn) ??…

2026/8/1 22:13:25 閱讀更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

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

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

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

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

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

AMAT 0100-02186 I/O 分配 PCB

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

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

Nissei Corp FFMN-32L-10-T0 40AX 三相異步電動機

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

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