简体   繁体   中英

Java singleton inner class

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

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();

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

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();
  }
}

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM