Singleton Pattern is one of the mostly known and used design pattern among all the GOF design patterns.
Principles of a Singleton Object:
- There exists one and only one instance of this object
- The state of the object is shared across all the threads in the VM
- In most cases data synchronization is done, unless there it is not needed (Not a Must)
In this Gist i would like to share the best possible way of creating a Singleton Object.
public class SampleObject {
private static class SampleObjectSingleton{
private static final SampleObject instance = new SampleObject();
public static SampleObject getInstance(){
return instance;
}
}
/* Private Constructor is a must for any Singleton Object */
private SampleObject(){}
/* A method to get access to the instance of this Singleton object */
public static SampleObject getInstance(){
return SampleObjectSingleton.getInstance();
}
// More Business methods
}
Benefits of the above format
- The object instance is created only once, as it is created as a static final reference of inner class.
- The object will not be created unless, a getInstance() method on SampleObject is called
- Loading the class will not create an instance, as the inner class will not be instantiated until its used.
I have also discussed several other ways of creating the Singleton objects along with the advantages and disadvantages in my [blog post] (http://www.novicehacks.info/2014/02/singleton-pattern.html) on singleton pattern.
Hope this helps. -- Sharath