您的位置:首页 > 其它

设计模式之单例模式

2016-05-30 19:22 197 查看

单例模式概要

单例的线程安全性( 懒加载会产生线程安全性)

单例加载,是否懒加载(使用时才生成对象)

以下只讨论懒加载

线程安全的解决

线程的不安全性在于singleInstance==null 的判断,如果两个线程同时执行这步,就会产生两个对象,破坏了单例。

public class SingleInstance {
private static SingleInstance singleInstance;
private SingleInstance() {
}
public static SingleInstance get(){
if(singleInstance==null){
singleInstance=new SingleInstance();
}
return singleInstance;
}
}


低效率锁

public static synchronized SingleInstance get(){
if(singleInstance==null){
singleInstance=new SingleInstance();
}
return singleInstance;
}


常用的dcl 双检测锁。省略了在mInstance!=null时的同步。

如果希望更安全可以,使用volatile 关键字。

public static  SingleInstance get(){
if(singleInstance==null) {
synchronized (SingleInstance.class){
if (singleInstance == null) {
singleInstance = new SingleInstance();
}
}
}
return singleInstance;
}


静态内部类单例模式,第一次加载Singleton 类时不会加载SingleetonHodler 类,第一次调用getInstance 方法会导致虚拟机加载SingletonHolder 类。 虚拟机能够保证线程安全。

public class Singleton {
private Singleton(){}
public static Singleton getInstance(){
return  SingletonHolder.sInstance;
}
private static class SingletonHolder{
private static final Singleton sInstance =new Singleton();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息