设计模式学习与应用——单例模式

单例模式

做用:一个类只有一个实例,而且提供访问该实例的全局访问点java

建立方式

1.懒汉方式spring

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.饿汉方式this

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依赖注入时使用的是“双重加锁”的单例模式code

双重加锁:

1.若是单例已经存在,则返回这个实例
2.若是单例为null,进入同步块进行加锁,生成单例对象

应用场景

1.须要生成惟一序列的环境
 2.须要频繁实例化而后销毁的对象。
 3.建立对象时耗时过多或者耗资源过多,但又常常用到的对象。
 4.方便资源相互通讯的环境资源

相关文章
相关标签/搜索