1. 懒汉式非线程安全
public class Singleton {
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 懒汉式线程安全
public class Singleton {
private Singleton() {}
private static Singleton instance;
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. 饿汉式
public class Singleton {
private Singleton() {}
private static Singleton instance = new Singleton();
public synchronized static Singleton getInstance() {
return instance;
}
}
4. 双重校验锁(double-checked)
public class Singleton {
private Singleton() {}
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
5. 静态类内部类
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6. 枚举
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}