Singleton pattern in java
Although Singletons are not encouraged because it can make it difficult to test it's clients, we can create it in three ways.
With Static factory
With Enum
In Effective Java ,Joshua Bloch encourage to use Enum for Singleton because it is more concise,provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation,even in the face of sophisticated serialization or reflection attacks.
- With Public final filed
- With Static Factory
- With Enum
With Public final filed
public class Cache {
public static final Cache INSTANCE = new Cache();
private static Map<String, Object> map = new HashMap<>();
private Cache() {
}
public void put(String key, Object data) {
map.put(key, data);
}
public Object get(String key) {
return map.get(key);
}
}
With Static factory
public class Cache {
private static final Cache INSTANCE = new Cache();
private static Map<String, Object> map = new HashMap<>();
private Cache() {
}
public void put(String key, Object data) {
map.put(key, data);
}
public Object get(String key) {
return map.get(key);
}
public static Cache getInstance(){
return INSTANCE;
}
}
With Enum
public enum Cache {
INSTANCE;
private static Map<String, Object> map = new HashMap<>();
public void put(String key, Object data) {
map.put(key, data);
}
public Object get(String key) {
return map.get(key);
}
}
In Effective Java ,Joshua Bloch encourage to use Enum for Singleton because it is more concise,provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation,even in the face of sophisticated serialization or reflection attacks.
0 comments:
Post a Comment