Java怎么实现单例模式?

  • 懒汉式:懒加载,线程不安全
public class Singleton { 
    private static Singleton singleton;

    private Singleton() { }

    public static Singleton getInstance() {

        if (singleton == null)

        singleton = new Singleton();

        return singleton; 
    }
}
  • 懒汉式线程安全版:同步效率低
public class Singleton {
    private static Singleton singleton;

    private Singleton() {
    }

    public synchronized static Singleton getInstance() {

      if (singleton == null) singleton = new Singleton();
      return singleton;

    }
}
  • 饿汉式:
public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
      return singleton;
    }
}
  • 饿汉式变种:
public class Singleton {

    private static Singleton singleton;

    static {
        singleton = new Singleton();
    }

    private Singleton() {
    }

    public static Singleton getInstance() {
        return singleton;
    }
}
  • 静态内部类方式:利用 JVM 的加载机制,当使用到 SingletonHolder 才会进行初始化。
public class Singleton {

    private Singleton() {
    }

    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.singleton;
    }

}
  • 枚举:
public enum Singletons {
    INSTANCE; // 此处表示单例对象里面的各种方法 

    public void Method() {
    }
}
  • 双重校验锁:
public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getInstance() {

        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}