Monday, June 19, 2017

Singleton Class in Java

Here is the example of complete singleton class which implements Cloenable and Serializable as well.

Read inline java comments for more details

package com.nitesh;

import java.io.Serializable;
/**
 * This class returns singleton Object and tries to handle all possible cases to avoid
 * creating multiple instance of MySingleton Class
 * Following given steps 
 * 1) Created INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
 * 2) Provide public static method that returns same INSTANCE of class every time
 * 3) Create private constructor so that no-one create object from outside of class
 * 4) Providing private constructor helps to suppress creating objects either by new operator/keyword or refection API & newInstance() method
 * 5) Implementing Serializable interface, and override readResolve() method and return same INSTANCE
 * 6) Implementing Cloneable interface and overridden clone() method and throw CloneNotSupportedException();
 *  @author Nitesh.Gupta
 *
 */
public class MySingleton implements Cloneable, Serializable {

private static final long serialVersionUID = 1L;
/**
* Creating a INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier
* and with EAGER Loading (creating object using new operator)
*/
private static MySingleton instance = new MySingleton();
/**
* Private constructor to avoid creating instance from outside class.
* Moreover, checking object reference if someone tries to create object using reflection.
*/
private MySingleton() {
if (instance == null) {
throw new IllegalStateException();
}
}
/**
* Static method for returning single object of MySingleton Object 
* @return Object of MySingleton
*/
public static MySingleton getInstance() {
return instance;
}
/**
* ReadResolve method to avoid creating new instance in case of De-serialization 
* @return same object
*/
public Object readResolve() {
return getInstance();
}
/**
* Overriding clone method throwing CloneNotSupportedException exception if 
* someone tries to clone this class
*/
@Override
protected Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}
}

No comments:

Post a Comment