Posts

Showing posts from January, 2014

Singleton Design Pattern

We need to create a class which can have only one instance at any time. Solution 1: public class MySingleton { private static MySingleton singleton= new MySingleton(); private MySingleton(){ System.out.println( "Object Created" ); } public static MySingleton getMySingleton(){ return singleton; } } Let's create the object when we need it, not at the time of loading the class. Solution 2(with Lazy loading): public class MySingleton { // Line : 1 private static MySingleton singleton=null; // Line : 2 private MySingleton(){ System.out.println( "Object Created" ); } // Line : 3 public static MySingleton getMySingleton(){ // Line : 4 if(singleton == null) // Line : 5 { singleton = new MySingleton();