-12

I am a one and half year experienced java developer. My question is :What is singleton? It seems that I never use it in my project(Java web,Spring boot ). I just cannot understand why and when should I use singleton. Sorry guys ,let me explain my confusion. A simple singleton class look like this:

class Singleton {

  private static Singleton instance;

  private Singleton(){
  }

  public static Singleton getInstance(){
     if(instance=null){
        instance=new Singleton();
     }

     return instance;
  }
  ........
}

Looks like there is not difference when I want to new a singleton object: Singleton s = new Singleton();

epicGeek
  • 72
  • 2
  • 10

1 Answers1

1

Singleton pattern gives you the control over the number of instances of the singleton class that can be instantiated. It is used numerous use cases.

The classic Java singleton looks just as you mentioned with a very important detail - the non public constructor.

The fact that the constructor is not public (either protected or private) will not allow anyone to create a new instance of singleton as you suggested:

Singleton singleton = new Singleton();

And that's the big difference than having just a regular class.

Note that such an implementation is not thread safe, and therefore you will either want to have it thread safe or non lazy initialized as follows:

  • Non lazy initialization

    public class Singleton {
        private static Singleton instance = new Singleton();
    
        private Singleton(){
        }
    
        public static Singleton getInstance(){
            return instance;
        }
    }
    
  • Thread safe

    public class Singleton {
        private static Singleton instance = null;
    
        protected Singleton() {
        }
    
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    
zuckermanori
  • 1,675
  • 5
  • 22
  • 31
  • Thank you very much.I noticed that once the Singleton class was loaded in JVM (maybe like this lol),the only one singleton class instance was created .When I call method 'getInstance',I always get the only instance.So,I think this is the meaning of the Singleton Pattern.Thank you again.God bless you! – epicGeek Jul 25 '17 at 06:23