单例模式
作用:一个类只有一个实例,并且提供访问该实例的全局访问点
创建方式
1.懒汉方式
public class Singleton{ //使外部无法访问这个变量,而要使用公共方法来获取 private static Singleton single = null; //只能单例类内部创建,所以使用私有构造器 private Singleton(){} //公共方法返回类的实例,懒汉式,需要第一次使用生成实例 //用synchronized关键字确保只会生成单例 public static synchronized Singleton getInstance(){ if(single == null){ single = new Singleton(); } return single; }}
2.饿汉方式
public class Singleton{ //类装载时构建实例保存在类中 private static Singleton single = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return single; }}
Spring中的单例
protected Object getSingleton(String beanName, boolean allowEarlyReference) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {//1 synchronized (this.singletonObjects) {//2 singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { ObjectFactory singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return (singletonObject != NULL_OBJECT ? singletonObject : null); }
spring依赖注入时使用的是“双重加锁”的单例模式
双重加锁:
1.如果单例已经存在,则返回这个实例
2.如果单例为null,进入同步块进行加锁,生成单例应用场景
1.需要生成唯一序列的环境
2.需要频繁实例化然后销毁的对象。 3.创建对象时耗时过多或者耗资源过多,但又经常用到的对象。 4.方便资源相互通信的环境