当前位置: 首页 > news >正文

设计模式--spring中用到的设计模式

一、单例模式(Singleton Pattern)

  • 定义:确保一个类只有一个实例,并提供全局访问点

  • Spring中的应用:Spring默认将Bean配置为单例模式

  • 案例:

@Component
public class MySingletonBean {// Spring 默认将其管理为单例
}
  • 在spring容器中,MySingletonBean只会有一个实例

二、工厂模式(Factory Pattern)

  • 定义:定义一个创建对象的接口,由子类决定实例化哪个类

  • spring中的应用:BeanFactory和ApplicationContext是工厂模式的实现

  • 案例:

@Configuration
public class AppConfig {@Beanpublic MyBean myBean() {return new MyBean();}
}
  • AppConfig是一个工厂类,myBean()方法负责创建MyBean实例

三、原型模式(Prototype Pattern)

  • 定义:通过复制现有对象来创建新对象

  • Spring中的应用:通过@Scope("prototype")配置Bean为原型模式

  • 案例

@Component
@Scope("prototype")
public class MyPrototypeBean {// 每次获取时都会创建一个新实例
}

四、模板方法模式(Template Method Pattern)

  • 定义:定义一个算法的骨架,将某些步骤延迟到子类中实现

  • Spring中的应用:JdbcTemplate、RestTemplate等

  • 案例:

@Autowired
private JdbcTemplate jdbcTemplate;
​
public void queryData() {String sql = "SELECT * FROM users";jdbcTemplate.query(sql, (rs, rowNum) -> {System.out.println(rs.getString("username"));return null;});
}

五、适配器模式(Adapter Pattern)

  • 定义:将一个类的接口转换成客户端期望的另一个接口

  • spring中的应用:Spring MVC中的HandlerAdapter

  • 案例:

@Controller
public class MyController {@RequestMapping("/hello")public String hello() {return "Hello, World!";}
}

六、装饰者模式(Decorator Pattern)

  • 定义:动态地为对象添加额外的职责

  • spring中的应用:spring AOP中的代理

  • 案例:

@Aspect
@Component
public class LoggingAspect {@Before("execution(* com.example.service.*.*(..))")public void logBefore(JoinPoint joinPoint) {System.out.println("Before method: " + joinPoint.getSignature().getName());}
}
  • AOP通过装饰者模式为方法添加日志功能

七、观察者模式(Observer Pattern)

  • 定义:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖对象都会收到通知

  • spring容器中的应用:Spring的事件机制

  • 案例:

@Component
public class MyEventListener implements ApplicationListener<MyEvent> {@Overridepublic void onApplicationEvent(MyEvent event) {System.out.println("Event received: " + event.getMessage());}
}
​
@Component
public class MyEventPublisher {@Autowiredprivate ApplicationEventPublisher publisher;
​public void publishEvent(String message) {publisher.publishEvent(new MyEvent(this, message));}
}
  • MyEventPublisher发布事件,MyEventListener监听并处理

八、代理模式(Proxy Pattern)

  • 定义:为其他对象提供一个代理以控制对这个对象的访问

  • Spring中的应用:SpringAOP和动态代理

  • 案例:

@Service
public class MyService {public void doSomething() {System.out.println("Doing something...");}
}
​
@Aspect
@Component
public class MyAspect {@Around("execution(* com.example.service.MyService.*(..))")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("Before method");Object result = joinPoint.proceed();System.out.println("After method");return result;}
}
  • AOP通过代理模式为MyService的方法添加额外逻辑

九、组合模式(Composite Pattern)

  • 定义:将对象组合成树形结构以表示"部分-整体"的层次结构

  • spring中的应用:Spring Security的过滤器链

  • 案例:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/private/**").authenticated();}
}
  • Spring Security将多个过滤器组合成一个过滤器链

十、策略模式(Strategy Pattern)

  • 定义:定义一系列算法,将它们封装起来,并使它们可以互相替换

  • Spring中的应用:Spring的资源加载策略(ResourceLoader)

  • 案例:

@Autowired
private ResourceLoader resourceLoader;
​
public void loadResource() {Resource resource = resourceLoader.getResource("classpath:data.txt");System.out.println("Resource loaded: " + resource.exists());
}
  • ResourceLoader根据不同的资源加载策略加载资源(如文件系统、类路径等)。

http://www.lryc.cn/news/545073.html

相关文章:

  • Qt控件中函数指针使用的最终版本,使用std::function
  • Java中的泛型类 --为集合的学习做准备
  • 6.6.6 嵌入式SQL
  • 基于C#的CANoe CLR Adapter开发指南
  • 【Qt】MVC设计模式
  • 【手撕算法】支持向量机(SVM)从入门到实战:数学推导与核技巧揭秘
  • JAVA面试常见题_基础部分_Dubbo面试题(上)
  • CSS—隐藏元素:1分钟掌握与使用隐藏元素的方法
  • 二、双指针——5. 移动零
  • 论文笔记-NeurIPS2017-DropoutNet
  • php 对接mqtt 完整版本,订阅消息,发送消息
  • 谈谈 ES 6.8 到 7.10 的功能变迁(6)- 其他
  • 【苍穹外卖】问题笔记
  • 脑机接口SSVEP 信号特征提取技术术语
  • 【Veristand】Veristand 预编写教程目录
  • C#光速入门的指南
  • 深入探索 STM32 微控制器:从基础到实践
  • Oracle性能调优(一):时间模型统计
  • 前端Npm面试题及参考答案
  • 记一次线上Tomcat服务内存溢出的问题处理
  • nist关于rsa中p,q的要求
  • Vue3项目如何使用TailWind CSS保姆级教程
  • NO.22十六届蓝桥杯备战|一维数组|七道练习|冒泡排序(C++)
  • Mysql的索引失效
  • 现代前端框架渲染机制深度解析:虚拟DOM到编译时优化
  • set 和 map 的左右护卫 【刷题反思】
  • 【Linux高级IO】多路转接(poll epoll)
  • Linux上用C++和GCC开发程序实现两个不同PostgreSQL实例下单个数据库中多个Schema稳定高效的数据迁移到其它PostgreSQL实例
  • Linux下的网络通信编程
  • Windows在多网络下指定上网接口