SingleTon Pattern :
Questions will be anserwed in this post
What is Singleton
Why do we need SingleTon
How can a class behaves singleTon
How can we fail singleton concept through serialization, how can we solve it..
For a given class, if only one instance needs to be created, we will go for this pattern.
why is SingleTon needed : there are some requirements, where only one class needs to be created, for example, database connection object,
for an application, only one database is needed, for this kind of situations, we go for singleTon.
If we restrict constructor as private , no one can create object,
instead provide one method to give instance, this method will create a object if it didnt exists, else creates object and returns it.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
Through Serialization, lets say we need to serialize singleTon class, and deserialize n number of times , you can get n number of objects, which is failing singleTon principle, How can we restrict this
In order to make serialization and singleton work properly,we have to introduce readResolve() method in the singleton class.readResolve() method lets developer control what object should be returned on deserialization.
For the current SingleObject singleton class,readResolve() method will look like this.
/**
* Special hook provided by serialization where developer can control what object needs to sent.
* However this method is invoked on the new object instance created by de serialization process.
* @return
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException{
return INSTANCE;
}
You need to implement readResolve method in your Singleton class. This small thing is used to override what serialization mechanism has created. What you return there will be used instead of data that came from serialization
but readResolve will work properly only if all fields are transient,
The best way to do this is to use the enum singleton pattern:
public enum SingleObject {
instance;
}
more details will be posted further