单例模式

落花浮王杯 提交于 2020-01-19 15:49:56

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;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!