Singleton pattern is required when we want to create only 1 instance of the class through out the application. There are many ways to create a singleton class and, so many loopholes/ways to break the Singleton behavior. We have to consider below points before writing the code.
1) Creation of Object Should be lazy.
2) Same object should be returned while deserializing
3) It should not allow to create a object using reflection
4) It should not allow to create new object through clone method
5) It should be thread safe.
Code:
public class Singleton implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton singleton=MySingleton.INSTANCE;
private static class MySingleton {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
if (singleton != null) {
throw new RuntimeException("Can't instantiate singleton twice");
}
}
public static Singletone getInstance() {
return MySingleton.INSTANCE;
}
protected Object readResolve() {
return getInstance();
}
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
1) Creation of Object Should be lazy.
2) Same object should be returned while deserializing
3) It should not allow to create a object using reflection
4) It should not allow to create new object through clone method
5) It should be thread safe.
Code:
public class Singleton implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton singleton=MySingleton.INSTANCE;
private static class MySingleton {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
if (singleton != null) {
throw new RuntimeException("Can't instantiate singleton twice");
}
}
public static Singletone getInstance() {
return MySingleton.INSTANCE;
}
protected Object readResolve() {
return getInstance();
}
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
No comments:
Post a Comment