Spring中的八大设计模式详解

📅 2026/8/1 21:38:22 👁️ 阅读次数 📝 编程学习
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.stock=100;}publicintgetStock(){returnstock;}publicvoiddecreaseStock(intquantity){if(stock>=quantity){stock-=quantity;}}}@ConfigurationpublicclassAppConfig{@Bean@Scope("singleton")// 默认就是单例,可省略publicProductInventoryManagerproductInventoryManager(){returnnewProductInventoryManager();}}

2. 工厂模式(Factory Pattern)

知识点总结
  • 概念:定义一个创建对象的接口,让子类决定实例化哪个类。Spring 中的BeanFactoryApplicationContext就是工厂模式的典型应用,它们负责创建和管理 Bean 对象。
  • 优点:将对象的创建和使用分离,提高代码的可维护性和可扩展性。
  • Spring 实现:通过配置文件或注解定义 Bean 的创建方式,Spring 容器根据这些配置创建 Bean 实例。
代码示例
importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;// 商品服务接口interfaceProductService{StringgetProductInfo();}// 具体商品服务实现类classElectronicsProductServiceimplementsProductService{@OverridepublicStringgetProductInfo(){return"This is an electronics product.";}}classClothingProductServiceimplementsProductService{@OverridepublicStringgetProductInfo(){return"This 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);}}// 切面类@Aspect@ComponentclassProductServiceAspect{@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]);}}@Configuration@EnableAspectJAutoProxy@ComponentScan(basePackages="com.example")publicclassAppConfig{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(AppConfig.class);ProductServiceproductService=context.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.oldProductService=oldProductService;}@OverridepublicvoidnewSellProduct(StringproductId){oldProductService.oldSellProduct(productId);}}

5. 装饰器模式(Decorator Pattern)

知识点总结
  • 概念:动态地给一个对象添加一些额外的职责。Spring 中的TransactionAwareCacheDecorator就是装饰器模式的应用,它在缓存对象的基础上添加了事务管理的功能。
  • 优点:比继承更灵活,可以在运行时动态地添加或删除功能。
  • Spring 实现:通过创建装饰器类,包装目标对象并添加额外的功能。
代码示例
// 商品服务接口interfaceProductService{StringgetProductInfo();}// 具体商品服务实现类classBasicProductServiceimplementsProductService{@OverridepublicStringgetProductInfo(){return"Basic product information.";}}// 装饰器抽象类abstractclassProductServiceDecoratorimplementsProductService{protectedProductServiceproductService;publicProductServiceDecorator(ProductServiceproductService){this.productService=productService;}}// 具体装饰器类,添加额外信息classPremiumProductServiceDecoratorextendsProductServiceDecorator{publicPremiumProductServiceDecorator(ProductServiceproductService){super(productService);}@OverridepublicStringgetProductInfo(){returnproductService.getProductInfo()+" - Premium features included.";}}

6. 观察者模式(Observer Pattern)

知识点总结
  • 概念:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。Spring 中的事件机制就是基于观察者模式实现的,如ApplicationEventApplicationListener
  • 优点:实现了对象之间的解耦,提高了系统的可维护性和可扩展性。
  • 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.orderId=orderId;}publicStringgetOrderId(){returnorderId;}}// 订单创建事件监听器类classOrderCreatedEventListenerimplementsApplicationListener<OrderCreatedEvent>{@OverridepublicvoidonApplicationEvent(OrderCreatedEventevent){System.out.println("Order created: "+event.getOrderId());}}// 订单服务类,发布订单创建事件classOrderService{privateAnnotationConfigApplicationContextcontext;publicOrderService(AnnotationConfigApplicationContextcontext){this.context=context;}publicvoidcreateOrder(StringorderId){OrderCreatedEventevent=newOrderCreatedEvent(this,orderId);context.publishEvent(event);}}@ConfigurationpublicclassAppConfig{publicstaticvoidmain(String[]args){AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(AppConfig.class);OrderServiceorderService=newOrderService(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.paymentStrategy=paymentStrategy;}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(){DriverManagerDataSourcedataSource=newDriverManagerDataSource();dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost:3306/ecommerce");dataSource.setUsername("root");dataSource.setPassword("password");jdbcTemplate=newJdbcTemplate(dataSource);}// 模板方法,定义查询商品的基本步骤publicfinalStringgetProductInfo(StringproductId){// 执行查询操作Stringsql=getSql();returnjdbcTemplate.queryForObject(sql,String.class,productId);}// 抽象方法,由子类实现具体的 SQL 语句protectedabstractStringgetSql();}// 具体的商品数据访问类classProductDaoextendsAbstractProductDao{@OverrideprotectedStringgetSql(){return"SELECT product_info FROM products WHERE product_id = ?";}}