public class SingletonDemo {
// 双重检测锁 public static class Singleton1 { private static volatile Singleton1 instance; private Singleton1() {} public static Singleton1 getInstance() { if (instance == null) { synchronized (Singleton1.class) { if (instance == null) { instance = new Singleton1(); } } } return instance; } } // 静态内部类 public static class Singleton2 { private static class Holder { private static Singleton2 instance = new Singleton2(); } private Singleton2() {} public static Singleton2 getInstance() { return Holder.instance; } } // 枚举类 public enum Singleton3 { INSTANCE; Singleton3() {} } }