Skip to main content

Posts

Showing posts from January, 2015

Singleton Pattern revisited

As the name suggest, Singleton Pattern restricts to the creation of one and only one object of a class. This is very useful whenever we want to restrict the creation of an object to single instance . This is very small and sweet type pattern that is used in many cases. Let's take an example and see how it is used in the code public class SingleObject { private static SingleObject singleObject; private SingleObject() { } public static SingleObject createInstance() { if (singleObject == null) { singleObject = new SingleObject(); } return singleObject; } } Line by line explanation Line 2 : creates private instance of the class Line 4 : constructor is private, so that no outer class can create object of this class Line 7 : creating a static method to get an instance of the class. We have defined method as static so that we don't need to create a object to call this method. Since it is static we can call this method by name of the class i.e. SingleO