第一种(静态内部类):
public class Singleton {
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
第二种(枚举)
public class EnumSingleton{
private EnumSingleton(){}
public static EnumSingleton getInstance(){
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton{
INSTANCE;
private EnumSingleton singleton;
//JVM会保证此方法绝对只调用一次
private Singleton(){
singleton = new EnumSingleton();
}
public EnumSingleton getInstance(){
return singleton;
}
}
}
第三种(双重校验锁) //JDK 1.5之后,双重检查锁才能达到正常的单例效果(1.5之前volatile 关键字使用有问题)
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {}
public static Singleton getIntance() {
if(singleton == null) {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
网友评论