+ 1
What is the best way to create a singleton class in java?
What is the best way to create a singleton class in java?
4 Respostas
+ 3
Here are a few of the singleton design pattern constructs. As to which is best, it depends on how you're using it and is otherwise subjective.
// Lazy Initialization
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
// Thread safe
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
//Thread safe with locking
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
// Helper class "Bill Pugh"
public class Singleton {
private Singleton() {}
private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton2();
}
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
// Eager Initialization
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
// Static Block
public class Singleton {
private static Singleton instance;
private Singleton() {}
static {
instance = new Sigleton();
}
public static Singleton getInstance() {
return instance;
}
}
+ 1
i asked for creation of a singleton
0
Google Design Patterns for Java.