版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Qgwperfect/article/details/88781173
第一种:
public class Singleton1 {
private static volatile Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (null == instance) {
synchronized (Singleton1.class) {
if (null == instance) {
instance = new Singleton1();
}
}
}
return Singleton1.instance;
}
}
第二种:
public class Singleton2 {
private Singleton2() {
}
private static class InstanceHolder {
private static final Singleton2 instance = new Singleton2();
}
public static Singleton2 getInstance() {
return InstanceHolder.instance;
}
}
第三种:
public class Singleton3 {
private Singleton3() {
}
private enum Singleton{
INSTANCE;
private final Singleton3 instance;
Singleton() {
instance = new Singleton3();
}
public Singleton3 getInstance() {
return instance;
}
}
public static Singleton3 getInstance() {
return Singleton.INSTANCE.getInstance();
}
}
推荐第二种或者第三种。