Rohit Bajaj
asked on
Why is enum singleton a better approach than static factory
HI,
There are two ways of making a class singleton :
1) singleton with static factory
2) Enum singleton
In 1) to make the class serializable it is required to add a readResolve method like :
// readResolve method to preserve singleton property
private Object readResolve() {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}
But in 2) which is considered to be the best way to make a singleton this method overriding is not required.
why is this so that we dont need to override the readResolve method in an Enum singleton..
Although in 1) we will have to manually specify implements serializable which is not required in case of enum...
This is taken from : http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3
There are two ways of making a class singleton :
1) singleton with static factory
2) Enum singleton
In 1) to make the class serializable it is required to add a readResolve method like :
// readResolve method to preserve singleton property
private Object readResolve() {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}
But in 2) which is considered to be the best way to make a singleton this method overriding is not required.
why is this so that we dont need to override the readResolve method in an Enum singleton..
Although in 1) we will have to manually specify implements serializable which is not required in case of enum...
This is taken from : http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
But wont in case of Enums also when it will be serialized and then deserialized it will create a new object.. Causing singleton to be broken.. What makes enums to return the same object when it is deserialiezed..
I dont see the readResolve method in Enum.java class....
So how is it preventing creation of a new object when it will be deserialized..