双重判断的懒汉式
public class SingleTon {
//需要注意的是volatile
private static volatile SingleTon mInstance;
private SingleTon() {
}
public static SingleTon getInstance() {
if (mInstance == null) {
synchronized (SingleTon.class) {
if (mInstance == null) {
mInstance=new SingleTon();
}
}
}
return mInstance;
}
}
静态内部类实现的单例
public class SingletonWithInnerClass {
private SingletonWithInnerClass(){
}
private static class SingletonHolder{
private static SingletonWithInnerClass INSTANCE = new SingletonWithInnerClass();
}
public static SingletonWithInnerClass getInstance(){
return SingletonHolder.INSTANCE;
}
}
网友评论