美文网首页
单例模式

单例模式

作者: fengfancky | 来源:发表于2017-06-23 08:56 被阅读10次

    方式一:

    使用时才进行初始化,包括私有的构造方法,私有的全局静态变量,公有的静态方法。

    <pre>
    public class Singleton {
    private static Singleton instance;//私有静态变量

      //私有构造方法
      private Singleton() {
    
          System.out.println("初始化");
      }
    
      //公有静态方法,暴露使用
    
      public static Singleton getInstance() {
          if(instance ==null) {
              instance =new Singleton();
          }
      return instance;
      }
    

    }</pre>

    方式二:

    执行效率相对较高,在类加载时初始化,会浪费内存。

    <pre>
    public class Singleton{
    private static final Singleton instance =new Singleton();
    private Singleton() {
    System.out.println("初始化");
    }
    public static Singleton getInstance(){
    return instance;
    }
    }</pre>

    方式三:

    静态内部类实现,当Singleton 类被加载时,instance 还未被初始化。调用 getInstance 方法时,会显示加载 SingletonHolder 类,从而实例化 instance。
    <pre>
    public class Singleton {
    private static class SingletonHolder {
    private static final Singleton INSTANCE =new Singleton();
    }
    private Singleton() {
    System.out.println("初始化");
    }
    public static final Singleton getInstance() {
    return SingletonHolder.INSTANCE;
    }
    }</pre>

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/kpwqcxtx.html