设计模式之单例模式及其应用

一、 单例模式概述

Java中单例模式的定义是:一个类只有一个实例,而且自行实例化并且向整个系统提供这个实例。

优点:由于单例模式在内存中只有一个实例,减少了内存开支和系统的性能开销;单例模式可以避免对资源的多重占用。

 

二、单例模式的几种形式

1.  饿汉式单例

public class Singleton {
	private static final Singleton singleton= new Singleton();
	private Singleton(){
	}
	public Singleton getSingleton(){
		return singleton;
	}
}

饿汉式是线程安全的,在类开始加载的时候就完成了单例的初始化。线程安全在java并发编程实战中是这样定义的:当多个线程访问某个类时,不管运行时环境采用何种调度方式或者这些线程将如何交替执行,并且在主调代码中不需要任何额外的同步或者协同,这个类都能表现出正确的行为,那么就称这个类是线程安全的。

2.懒汉式单例

public class Singleton {
    private Singleton() {}
    private static Singleton single=null;
    public static Singleton getInstance() {
         if (single == null) {  
             single = new Singleton();
         }  
        return single;
    }
}

懒汉式不是线程安全的,并发环境下,可能出现多个single对象。要实现线程安全,可以采用双重锁:

public static Singleton getInstance() {
    if (singleton == null) {  
        synchronized (Singleton.class) {  
           if (singleton == null) {  
              singleton = new Singleton(); 
           }  
        }  
    }  
    return singleton; 
}

三、单例模式在spring中的应用

DefaultSingletonBeanRegistry类中的getSingleton方法:

/** Cache of singleton objects: bean name --> bean instance */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

	/** Cache of singleton factories: bean name --> ObjectFactory */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);

	/** Cache of early singleton objects: bean name --> bean instance */
	private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);

	
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	// map缓存中查看是否存在实例
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				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在获取单例bean的时候,采用了双重判断加锁的单例模式,首先尝试从map缓存singletonObjects中获取实例,如果获取不到,对singletonObjects加锁,再到map缓存earlySingletonObjects里面获取,如果还是为null,就创建一个bean,并放到earlySingletonObjects中去。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值