[Solved] What is singleton pattern?Why and When should I use it? [duplicate]


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

1

solved What is singleton pattern?Why and When should I use it? [duplicate]