1.工厂模式
Spring中使用的最常见的设计模式是工厂模式。Spring使用工厂模式来创建和管理对象,以及依赖注入。这种模式允许我们编写代码,不直接创建对象,而是使用工厂方法来创建对象。在Spring中,IOC容器被视为一个工厂,它负责创建和管理对象,以及依赖注入。
例子:浅谈Spring框架应用的设计模式(一)——工厂模式_spring工厂模式_猿梦学码的博客-CSDN博客
2.代理模式
Spring使用代理模式来实现AOP编程,以实现对目标对象的横切关注点的动态代理。Spring支持JDK动态代理和CGLIB动态代理两种类型的代理。
3.单例模式
在默认情况下,Spring使用单例模式来创建和管理无状态的Bean对象。单例模式是一种创建型模式,它确保在应用程序的生命周期中,只创建一个实例。
单例模式的懒汉方式
public class Singleton01 {
private static Singleton01 instance;
private Singleton01(){
}
public static synchronized Singleton01 getInstance(){
if (null==instance){
instance=new Singleton01();
}
return instance;
}
}
测试类
public class TestSingleton01 {
public static void main(String[] args) {
Thread thread1=new Thread(()->{
for (int i = 0; i <100 ; i++) {
try {
Singleton01 s=Singleton01.getInstance();
System.out.println(s.hashCode());
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2=new Thread(()->{
for (int i = 0; i <100 ; i++) {
try {
Singleton01 s=Singleton01.getInstance();
System.out.println(s.hashCode());
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread3=new Thread(()->{
for (int i = 0; i <100 ; i++) {
try {
Singleton01 s=Singleton01.getInstance();
System.out.println(s.hashCode());
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
thread3.start();
}
}
线程的安全性问题
懒汉模型是线程不安全的
单例模式的饿汉模式
public class Singleton02 {
private static Singleton02 instance=new Singleton02();
private Singleton02(){
}
public static Singleton02 getInstance(){
return instance;
}
}
枚举法
public enum Singleton03 {
INSTANCE;
}
4.模板方法模式
Spring对一些通用的操作,比如查询数据库、事务控制等,使用了模板方法模式。Spring提供了一些模板类来处理具体的业务逻辑,实现非常方便,开发者只需要实现特定的模板方法即可。
例子:Spring中的设计模式:模板方法模式_spring 模板方法_不才陈某的博客-CSDN博客
5.观察者模式
Spring使用观察者模式来实现事件监听和处理器的通用注册和调用机制。Spring通过ApplicationEvent类和ApplicationEventPublisher接口实现观察者模式。开发者只需要在观察者类中注册自己感兴趣的事件,就可以监听到事件并进行相应的处理。
例子:Spring中的观察者模式_spring 观察者模式_恼书:-(空寄的博客-CSDN博客
6.适配器模式
Spring集成了多种不同的技术和框架,其中很多都是通过适配器模式来进行集成的。适配器模式通过封装不同的技术和框架之间的差异,提供一个统一的接口。
例子:【源码分析设计模式 10】SpringMVC中的适配器模式_spring 适配器模式_哪 吒的博客-CSDN博客
7.策略模式
Spring的注解驱动开发就是一种典型的策略模式的应用,通过注解来定义不同的策略,并使用反射来动态选择策略。开发者只需要在Java方法或类上添加特定的注解,就可以定义不同的策略。
例子:【源码分析设计模式 11】SpringMVC中的策略模式_spring 策略模式_哪 吒的博客-CSDN博客
8.组合模式
Spring的Bean的作用域管理就是一个典型的组合模式的应用,通过组合不同的作用域来实现不同级别的Bean的管理。开发者可以通过注解或XML配置文件来指定Bean的作用域,Spring IoC容器会自动根据作用域来管理和创建Bean实例。