Spring中的八大设计模式详解
Spring 框架中运用了多种设计模式下面为你详细介绍 Spring 框架中常见的八大设计模式及相关代码示例1. 单例模式Singleton Pattern知识点总结概念确保一个类只有一个实例并提供一个全局访问点。在 Spring 中默认情况下Bean 的作用域是单例的即整个应用程序中只有一个实例。优点节省系统资源减少对象创建和销毁的开销。Spring 实现Spring 容器负责管理单例 Bean 的生命周期通过内部的缓存机制确保一个 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知识点总结概念定义一个创建对象的接口让子类决定实例化哪个类。Spring 中的BeanFactory和ApplicationContext就是工厂模式的典型应用它们负责创建和管理 Bean 对象。优点将对象的创建和使用分离提高代码的可维护性和可扩展性。Spring 实现通过配置文件或注解定义 Bean 的创建方式Spring 容器根据这些配置创建 Bean 实例。代码示例importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;// 商品服务接口interfaceProductService{StringgetProductInfo();}// 具体商品服务实现类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面向切面编程就是基于代理模式实现的通过代理对象在目标对象的方法前后添加额外的逻辑如日志记录、事务管理等。优点可以在不修改目标对象代码的情况下增强其功能。Spring 实现Spring AOP 支持两种代理方式JDK 动态代理基于接口和 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);}// 具体商品服务实现类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就是适配器模式的应用它将不同类型的处理器适配成统一的处理方式。优点使原本由于接口不兼容而不能一起工作的那些类可以一起工作。Spring 实现通过实现不同的HandlerAdapter来适配不同类型的处理器。代码示例// 旧的商品服务接口interfaceOldProductService{voidoldSellProduct(StringproductId);}// 旧的商品服务实现类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知识点总结概念动态地给一个对象添加一些额外的职责。Spring 中的TransactionAwareCacheDecorator就是装饰器模式的应用它在缓存对象的基础上添加了事务管理的功能。优点比继承更灵活可以在运行时动态地添加或删除功能。Spring 实现通过创建装饰器类包装目标对象并添加额外的功能。代码示例// 商品服务接口interfaceProductService{StringgetProductInfo();}// 具体商品服务实现类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知识点总结概念定义对象间的一种一对多的依赖关系当一个对象的状态发生改变时所有依赖它的对象都会得到通知并自动更新。Spring 中的事件机制就是基于观察者模式实现的如ApplicationEvent和ApplicationListener。优点实现了对象之间的解耦提高了系统的可维护性和可扩展性。Spring 实现通过定义事件类和监听器类当事件发布时监听器会接收到通知并执行相应的操作。代码示例importorg.springframework.context.ApplicationEvent;importorg.springframework.context.ApplicationListener;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importorg.springframework.context.annotation.Configuration;// 订单创建事件类classOrderCreatedEventextendsApplicationEvent{privateStringorderId;publicOrderCreatedEvent(Objectsource,StringorderId){super(source);this.orderIdorderId;}publicStringgetOrderId(){returnorderId;}}// 订单创建事件监听器类classOrderCreatedEventListenerimplementsApplicationListenerOrderCreatedEvent{OverridepublicvoidonApplicationEvent(OrderCreatedEventevent){System.out.println(Order created: event.getOrderId());}}// 订单服务类发布订单创建事件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就是策略模式的应用根据不同的资源类型选择不同的加载策略。优点可以在运行时动态地选择不同的算法提高了系统的灵活性。Spring 实现通过定义策略接口和具体的策略实现类根据不同的需求选择不同的策略。代码示例// 支付策略接口interfacePaymentStrategy{voidpay(doubleamount);}// 具体支付策略实现类 - 支付宝支付classAlipayPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Alipay.);}}// 具体支付策略实现类 - 微信支付classWechatPaymentStrategyimplementsPaymentStrategy{Overridepublicvoidpay(doubleamount){System.out.println(Paying amount via Wechat Pay.);}}// 订单服务类根据不同的支付策略进行支付classOrderService{privatePaymentStrategypaymentStrategy;publicOrderService(PaymentStrategypaymentStrategy){this.paymentStrategypaymentStrategy;}publicvoidprocessOrder(doubleamount){paymentStrategy.pay(amount);}}8. 模板方法模式Template Method Pattern知识点总结概念定义一个操作中的算法的骨架而将一些步骤延迟到子类中。Spring 中的JdbcTemplate就是模板方法模式的应用它定义了 JDBC 操作的基本步骤如获取连接、执行 SQL 语句、关闭连接等具体的 SQL 语句由子类实现。优点提高了代码的复用性避免了代码的重复编写。Spring 实现通过定义抽象类和具体的模板方法子类继承抽象类并实现具体的步骤。代码示例importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.jdbc.datasource.DriverManagerDataSource;// 抽象的商品数据访问类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){// 执行查询操作StringsqlgetSql();returnjdbcTemplate.queryForObject(sql,String.class,productId);}// 抽象方法由子类实现具体的 SQL 语句protectedabstractStringgetSql();}// 具体的商品数据访问类classProductDaoextendsAbstractProductDao{OverrideprotectedStringgetSql(){returnSELECT product_info FROM products WHERE product_id ?;}}

相关新闻

2026六盘水黄金回收白银回收铂金回收靠谱临街实体公安备案支持到店核验门店联系方式推荐

2026六盘水黄金回收白银回收铂金回收靠谱临街实体公安备案支持到店核验门店联系方式推荐

2026六盘水黄金白银铂金回收实测榜单|公安备案临街实体门店推荐 六盘水街头巷尾贵金属回收店铺遍地丛生,行业套路层出不穷,不少市民变现时遭遇虚高报价、克扣损耗、未经同意熔金压价等问题。为帮助本地居民规避消费陷阱,小编实地走…

2026/8/1 21:13:20 阅读更多
2025 年 3 月青少年软编等考 C 语言四级真题解析

2025 年 3 月青少年软编等考 C 语言四级真题解析

目录 T1. 两枚硬币 思路分析 T2. 完美数列 思路分析 T3. 多样解码 思路分析 T4. 二进制串的评分 思路分析 T1. 两枚硬币 题目链接:SOJ D1387 伊娃喜欢收集全宇宙的硬币,包括火星币等等。一天她到了一家宇宙商店,这家商店可以接受任何星球的货币,但有一个条件,无论什么价…

2026/8/1 21:13:20 阅读更多
告别Origin熬夜画图❗️论文科研绘图一键出高清版图✅

告别Origin熬夜画图❗️论文科研绘图一键出高清版图✅

谁懂理工科、实证论文的痛😭 论文内容写满了、数据全部算完了,最后卡死在科研绘图! Origin、Matlab零基础不会用,自学教程繁琐又耗时间; 自己手画图表粗糙廉价、配色杂乱、标注不规范; 网上找的图有水印…

2026/8/1 22:03:25 阅读更多
AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O 分配 PCB

AMAT 0100-02186 I/O分配PCB板是应用材料(Applied Materials)公司生产的一款用于半导体设备的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)品牌的一款工业用三相异步电机,适用于自动化设备及通用机械驱动。该型号(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)公司生产的一款用于半导体设备的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)品牌的一款工业用三相异步电机,适用于自动化设备及通用机械驱动。该型号(FFMN-32L-10-T0 40AX)的核心特点如下:三相交流异步电动机。额定…

2026/8/1 0:09:33 阅读更多