单例模式
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决:一个全局使用的类频繁地创建与销毁。
何时使用:当您想控制实例数目,节省系统资源的时候。
如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
关键代码:构造函数是私有的。
饿汉模式
饿汉模式,一开始就实例化好对象,天生安全,但占用一部分空间。
public final class SingletonStarve{
private static final SingletonStarve instance;
static{
instance = new SingletonStarve();
}
public static SingletonStarve getInstance(){
return instance;
}
private SingletonStarve(){}
}
懒汉模式-性能低
延迟初始化,按需加载,减少空间浪费,保证了线性安全。但调用getInstance()方法需要同步,并发性能低。
public class SingletonLazy{
private static SingletonLazy instance = null;
private SingletonLazy(){}
public static synchronized SingletonLazy getInstance(){
if(instance == null){
instance = new SingletonLazy();
}
return instance;
}
}
懒汉模式-双重校验锁-性能高
这个模式将同步内容下放到if内部,提高了执行效率,不用每次获取对象时都进行同步,只有第一次同步,创建了对象之后就没必要了。只有第一次会进去,之后instance不为空,直接返回instance。保证了线性安全,同时提高了性能。
public class SingletonLazy{
private static volatile SingletonLazy instance = null;
private SingletonLazy(){}
public static SingletonLazy getInstance(){
if(instance == null){
synchronized(SingletonLazy.class){
if(instance == null){
instance = new SingletonLazy();//可能会重排序
}
}
}
return instance;
}
}