Skip to main content

Ways to define Singleton Classes

Singleton classes comes under "Creational design pattern", Singleton pattern restricts from creating multiple instances of the class,and ensure that only one object should be available in the JVM, there are different ways to implement singleton classes as below :-

Ways to define Singleton classes :-

1. By defining the singleton class object as static final variable, this is known as early initialization of singleton object.
public class SingletoneClassExample{

Private static final instance = new SingletoneClassExample();

// Define private constructor to avoid other classes from creating instance
private SingletoneClassExample(){

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

}
By creating singleton class using above method the class object will be created at class loading itself, so if application is not using this class still the object will be created.

2. Define singleton class object on method call
public class SingletoneClassExample{

Private static final instance = null;

// Define private constructor to avoid other classes from creating instance

private SingletoneClassExample(){
}

public static SingletoneClassExample getInstance(){

  instance = new SingletoneClassExample();
  return instance;

   }

}
This is the simple way to create singleton object on demand, but it is safe only in case of single threaded applications, in case of multiple threads calls this method there may be chances to create multiple objects of singleton class.

3. Define Thread safe Singleton Classes :-
We can easily make the above class thread safe by making getInstance() method Synchronized
public class SingletoneClassExample{

Private static final instance = null;

// Define private constructor to avoid other classes from creating instance
private SingletoneClassExample(){
}

public static synchronized SingletoneClassExample getInstance(){
        instance = new SingletoneClassExample();
       return instance;
    }

}
Above solution works fine for thread safety but it reduces the performance because of global synchronized method which will be called always while all method calls though synchronization is needed only for first few cases.

4. Define Singleton by Double check Locking :-
public class SingletoneClassExample{

Private static final instance = null;

// Define private constructor to avoid other classes from creating instance
private SingletoneClassExample(){

}

// global method to get singleton obj

public static SingletoneClassExample getInstance(){

  if(instance == null){

       synchornized(SingletoneClassExample.class){ // use synchronized only if instance is null
             if(instance == null){
                   instance = new SingletoneClassExample();
             }
         }

     }
     return instance;
     }
}

5. Bill Pugh Singleton classes :-

Implementing singleton classes using static inner classes, static inner helper class wont initialize until getInstance() method gets called.
public class SingletoneClassExample{

// Define private constructor to avoid other classes from creating instance
private SingletoneClassExample(){
}

private static class SingletoneClassHelper{
    Private static final instance =  new SingletoneClassExample();  // loading of class will be synchronized here..

}

public static SingletoneClassExample getInstance(){
      return SingletoneClassHelper.instance ;
}
No synchronization required in this case so there will not be any performance issues, easy to use and understand..

Happy Coding.. :)

Comments

Popular posts from this blog

Launch an Android application on Bootup

If you want to start an android application on device restarts, you need to listen for BOOT_COMPLETED broadcast in the manifest file and launch the Launcher activity in onreceive of BOOT_COMPLETED broadcast receiver. Follow below steps to launch activity on device boot up :- 1. Register for Boot completed receiver in Android Manifest file. Add below Permission to receive BOOT_COMPLETED broadcast, <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> Register for Boot completed broadcast receiver , <receiver android:name="AppAutostartReceiver" android:enabled="true" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> 2. Add custom Broadcast receiver in the application, public class AppAutostartReceiver extends BroadcastReceiver { @Override public void onReceive(Context cont

Whitelist an android application on android 6.0/Marshmallow

Whitelist wont disable doze mode for your app, however can use network and hold wake lock. Whitelist an android application through code, boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName()); if(!isIgnoringBatteryOptimizations){   Intent intent = new Intent();   intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);   intent.setData(Uri.parse("package:" + getPackageName()));   startActivityForResult(intent, MY_IGNORE_OPTIMIZATION_REQUEST);   }                             Check for the result, @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     if (requestCode == MY_IGNORE_OPTIMIZATION_REQUEST) {          PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);          boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName());          if(isIgnoringBatteryOptimizations){             // Ignoring battery opti