The good:
public class SingletonObject
{
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if (ref == null) {
synchronized (SingletonObject .class) {
ref = new SingletonObject();
}
}
return ref;
}
private static volatile SingletonObject ref;
}
The good ++:
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
return ref;
}
private static final SingletonObject ref = new SingletonObject();
}
The better:
This technique doesn't require any special language constructs. So on that point of view this is better!
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.
* getInstance() or the first access to SingletonHolder.INSTANCE,
* not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
The best:
public enum SingletonObject {
INSTANCE;
}
According to Joshua Bloch:"a single-element enum type is the best way to implement a singleton for any version of Java that supports enum. This is concise and has no drawbacks regarding serializable objects which is challenging for other implementations.
No comments:
Post a Comment