单例

Java 单例

  • 非延迟加载单例类
public class Singleton {
  private Singleton(){}
  private static final Singleton instance = new Singleton();
  public static Singleton getInstance() {
    return instance;
  }
}
  • 简单的同步延迟加载
public class Singleton {

  private static Singleton instance = null;

  public static synchronized Singleton getInstance() {
    if (instance == null)
      instance  new Singleton();
    return instance;
  }
}
  • 双重检查成例延迟加载
public class Singleton {

  private static volatile Singleton instance = null;

  public static Singleton getInstance() {
    if (instance == null) {
        synchronized (Singleton.class) {
            if (instance == null) {
                instance  new Singleton();
            }
        }
    }
    return instance;
  }

}
  • 类加载器延迟加载
public class Singleton {
  private static class Holder {
    static final Singleton instance = new Singleton();
  }
  public static Singleton getInstance() {
    return Holder.instance;
  }
}

Links

https://blog.csdn.net/u011595939/article/details/79972371#4%E9%9D%99%E6%80%81%E5%86%85%E9%83%A8%E7%B1%BB%E6%96%B9%E5%BC%8F%E6%8E%A8%E8%8D%90

上一页
下一页