Java singleton inner class

怎甘沉沦 提交于 2019-12-10 15:24:44

问题


I know the concept of singleton in Java. I'm having problems with creating singleton as inner class in Java. Problem occurs at holder's

public class NormalClass {
    private class Singleton {
        private static Singleton instance = null;

        private Singleton() {
        }

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

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

    public void method1() {
        Singleton.getInstance();
    }
}

Error is at new Singleton() constructor call. How to proper call private constructor of Singleton as inner class?

Regards


回答1:


If it should be a real singleton, make your singleton class static. Then you will be able to call the constructor.

The reason why your constructor call does not work is explained in the Java nested classes tutorial. Basically, the inner class requires an instance of the outer class before it can be constructed:

private static Singleton sessionData = new NormalClass().new Singleton();



回答2:


You cannot declare static classes within a non-static class. Make the Singleton class static and everything should compile just fine.




回答3:


The problem is that the inner class is not static inner class,

public class NormalClass {
  private static class Singleton {
      private static Singleton instance = null;

      private Singleton() {
      }

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

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

  public void method1() {
      Singleton.getInstance();
  }
}



回答4:


Initialize on Demand.... Joshua Bloch..

I think if your inner class is static, your holder class should also be static.

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

Or Why not like this? why an inner holder class at all ?

public class NormalClass{
  private static class InnerClass{
    private static InnerClass instance = null;
    private InnerClass(){}
    public static InnerClass getInstance() {
  if(null==NormalClass.InnerClass.instance){
    NormalClass.InnerClass.instance = new InnerClass(); 
  }
  return NormalClass.InnerClass.instance;
}
  }

  public void test(){
    InnerClass.getInstance();
  }
}


来源:https://stackoverflow.com/questions/9031265/java-singleton-inner-class

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