1) Enum Singletons are easy to write
public enum EasySingleton{
INSTANCE;
}
2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example :
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
Java Enum's
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}
Enum singleton are perfect as soon as you don't need a singleton that inherit from something. In that case, you cannot use enum anymore and you must use other way...
Read full article from Why Enum Singleton are better in Java
public enum EasySingleton{
INSTANCE;
}
2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example :
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
Java Enum's
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}
Read full article from Why Enum Singleton are better in Java
No comments:
Post a Comment