Spring 中应用了哪些设计模式呢?
Spring 框架中用了蛮多设计模式的:

①、比如说工厂模式用于 BeanFactory 和 ApplicationContext,实现 Bean 的创建和管理。
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyBean myBean = context.getBean(MyBean.class);
②、比如说单例模式,这样可以保证 Bean 的唯一性,减少系统开销。
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService1 = context.getBean(MyService.class);
MyService myService2 = context.getBean(MyService.class);
// This will print "true" because both references point to the same instance
System.out.println(myService1 == myService2);
③、比如说 AOP 使用了代理模式来实现横切关注点(如事务管理、日志记录、权限控制等)。
@Transactional
public void myTransactionalMethod() {
// 方法实现
}
Spring如何实现单例模式?
Spring 通过 IOC 容器实现单例模式,具体步骤是:
单例 Bean 在容器初始化时创建并使用 DefaultSingletonBeanRegistry 提供的 singletonObjects 进行缓存。
// 单例缓存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
public Object getSingleton(String beanName) {
return this.singletonObjects.get(beanName);
}
protected void addSingleton(String beanName, Object singletonObject) {
this.singletonObjects.put(beanName, singletonObject);
}
在请求 Bean 时,Spring 会先从缓存中获取。
THE END
暂无评论内容