一般来说,单例模式有五种写法:懒汉、饿汉、双重检验锁、静态内部类、枚举。所说都是线程安全的实现。
一般情况下直接使用饿汉式就好了,如果明确要求要懒加载(lazy initialization)会倾向于使用静态内部类,如果涉及到反序列化创建对象时会试着使用枚举的方式来实现单例。
懒汉式
public final class Singleton {
private static Singleton instance;
private Singleton() {
//
}
public static Singleton getInstance() {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
return instance;
}
}
双重检验锁
public final class Singleton {
//用volatile修饰对象,禁止指令重排序优化
private volatile static Singleton instance;
private Singleton() {
//
}
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
饿汉式
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() {
//
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
枚举
public enum EnumSingleton {
INSTANCE;
private EnumSingleton() {
}
}