Tuesday, June 1, 2021

Singleton pattern

Well I was looking for information about the singleton pattern in Java.  The singleton pattern is used for classes which can have only one instance.

Let's follow the logic, we want one class to have only one object, the object is being created by the constructor, so I want to control when constructor is being called, the easiest way is to be me the only one that can call the constructor, so making the constructor private seems a good step. Once I have the instance then I have to give the possibility to get this instance by creating a getter.

But If I do not have the instance yet I cannot access the instance methods but only the static methods, so we can access them from the class.

public class MySingleton{
        private static MySingleton instance=new MySingleton();
    
        private MySingleton(){};

        public static MySingleton getInstance(){
            return instance;
        }
}

  1. Keep the constructor private
  2. initialize instance field with the private constructor
  3. create a getter to get the instance
But this implementation leads to the possibility to create more instances of MySingleton by extending the class, If I create a subclass of MySingleton for example MyMiniSingleton, then MyMiniSingleton is an instance also of MySingleton.


for more information: http://java.sun.com/developer/technicalArticles/Programming/singletons/