Java - Design Pattern - Singleton


Definition

Its a design pattern that restrict the instantiate of a class to only one object. It's a creational Design Pattern. 

Use

This is useful when only one object is needed to coordinate actions within the system. This may save the resources as in some situations the same object may be capable enough to serve and hence will protect from the hassle of constructing and destructing the objects.  

Implementation

Class TestSingleton {

      private static TestSingleton singletonObj = null;   

      private TestSingleton (){    // make constructor private
      }

      public static getSingletonObj(){
           if(singletonObj == null ){
                  singletonObj = new TestSingleton ();
           }
        return a;

      public doSomeWork(){    // implementation
      }
}

1. Make constructor private so that it can't be instantiated using new operator.
2. Have a static method to call constructor for object creation. It should be static as we have disabled object  creation from outside using new operator by making the constructor private.
3. Have a static reference to hold the object.
4. Have a logic within static method to instantiate object only if it hasn't already been created. If its created return the same object.

So now we can get the object using TestSingleton.getSingletonObj()

Synchronization problem with singleton

In the above example in a multithreaded environment we may have problem if 2 threads try to access getSingletonObj simultanously so one should have synchroned access to it 

Example -

Class TestSingleton {

      private static volatile TestSingleton singletonObj = null;   

      private TestSingleton (){    // make constructor private
      }

      public static getSingletonObj(){
           TestSingleton obj singletonObj ;
           if(obj == null) {
           synchronized(this) {    // while we were waiting for the lock, another 
                 obj singletonObj ;       // thread may have instantiated the object
                 if(obj == null) {  
                    obj = new TestSingleton();
                    singletonObj obj ;
                 }
            }
       }
      public doSomeWork(){    // implementation
      }
}


Implementing Singleton using all static members 

If we want to achieve this behavior, other thought that comes to mind is having all static members and static method doing the implementation. 

For ex -

Class TestSingleton {

      private final test;
      
      private TestSingleton (){    // make constructor private
           test = 5;
      }

      public static final doSomeWork(){    // implementation
      }
}

With this implementation -

1. We made constructor private so that no object can be instantiated from outside.
2. We can access TestSingleton.doSomeWork() for its implementation.

As each class just have one copy of static members , there will be just single space in memory and that will be reused each time but there are following flaws that limit's its usage for singleton behaviour.

a. Serialization - Static members belong to the class and hence can't be serialized.
b. Though we have made the constructor private, static member variables still will be carried to subclass.
c. We can't do lazy initialization as everything will be loaded upon class loading only.