October 08, 2018

Singleton class example in java

/**
 * In the Singleton class, when we first time call getInstance() method,
 *  it creates an object of the class and return it to the variable. 
 *  Since getInstance() is static, it is changed from null to some object.
 *   Next time, if we try to call getInstance() method,
 *    since single_instance is not null, it is returned to the variable,
 *     instead of instantiating the Singleton class again. 
 *     This part is done by if condition
 */
package com.belazy.algorithm;

/**
 * @author ravi shankar mullath
 * 
 */
public class SingletonClass {

private static SingletonClass singleton = null;
public String s = null;

/**
* I made default constructor as private
*/
private SingletonClass() {
s = "sachin tendulkar";
}

/**
* @param args
*/
public static SingletonClass getInstance() {
if (null == singleton)
singleton = new SingletonClass();
return singleton;
}

}


/**
 * 
 */
package com.belazy.algorithm;

/**
 * @author belazy
 *
 */
public class MainClass {

/**
* @param consumerfed kozhikode
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonClass x = SingletonClass.getInstance();
SingletonClass y = SingletonClass.getInstance();
SingletonClass z = SingletonClass.getInstance();
x.s = x.s.toUpperCase();
System.out.println(y.s);

}

}

Output


SACHIN TENDULKAR



Explanation


Here we made the default constructor as private. so this constructor cannot be access from outside the class. So i restricted created objects out side from singleton class.

A new instance of the class can be created only through getInstance() method
SingletonClass x = SingletonClass.getInstance();
While creating an instance it will check whether the instance is already created or not.






No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments