Singleton Design Pattern

The name is singleton design pattern it self tells us regarding what exactly this design pattern will do. Using singleton design pattern we can restrict the object or instance creation only to one instance. So using singleton design pattern only one instance/object of a class will get created.

Theoretical we will maintain only one instance of a class inside class. A simple singleton class will have variables, methods and constructor as per below diagram.



A simple singleton class will have a instance variable which will maintain the single instance of a class, the reason behind private constructor is that it will not allow object creation outside the class and finally the public get instance method to fetch the instance. Now let's see the java example for same.

 
public class SingleTon {
	
	private static SingleTon instance= new SingleTon();
	
	//private allowed object creation only inside the class
	private SingleTon() {

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

As you can see in the class, the getInstance() method is returning the static instance created while class is getting loaded. private constructor will restrict the object creation only inside the class.So outside class , it will not able possible to instantiate the object and whenever the object is needed it will be possible to retrieve it using the getInstance method.

Share this:

CONVERSATION

0 comments:

Post a Comment