标签:final instance nal bsp volatile single 静态 通过 gets
public class Singleton {
private volatile static Singleton instance = null;
private Singleton () {
}
public static Singleton getSingleton() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private static class SingletonInstance {
private static final Singleton instance = new Singleton();
}
private Singleton() {
}
public static Singleton getSingleton() {
return SingletonInstance.instance;
}
}
public class Singleton { private Singleton() {} public static Singleton getInstance() { return SingletonEnum.INSTANCE.getInstance(); } private static enum SingletonEnum { INSTANCE; private Singleton singleton = null; private SingletonEnum() { singleton = new Singleton(); } public Singleton getInstance() { return this.singleton; } } public static void main(String[] args) { Singleton singleton1 = Singleton.getInstance(); Singleton singleton2 = Singleton.getInstance(); System.out.println("singleton1==singleton2? " + (singleton1==singleton2)); } }
标签:final instance nal bsp volatile single 静态 通过 gets
原文地址:http://www.cnblogs.com/hellocyc/p/6754101.html