几种经典单例模式实现,参考:https://github.com/iluwatar/java-design-patterns
基础实现
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
利用内部类实现
public final class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private final static Singleton INSTANCE = new Singleton();
}
}
线程安全的懒加载实现
public final class Singleton {
private static Singleton INSTANCE;
private Singleton() {
// 避免通过反射方式再次初始化
if (INSTANCE == null) {
INSTANCE = this;
} else {
throw new IllegalStateException("Singleton already initialized!");
}
}
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
线程安全的双重检查实现
public final class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() {
// 避免通过反射方式再次初始化
if (INSTANCE != null) {
throw new IllegalStateException("Singleton already initialized!");
}
}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}