目录
懒汉式
线程不安全的单例模式
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
线程安全的单例模式
public class SingletonSafe {
private static volatile SingletonSafe singleton;
private SingletonSafe() {
}
public static SingletonSafe getSingleton() {
if (singleton == null) {
synchronized (SingletonSafe.class) {
if (singleton == null) {
singleton = new SingletonSafe();
}
}
}
return singleton;
}
}
饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
静态内部类实现单例模式
public class Singleton {
private static class SingletonHoler {
private static Singleton instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHoler.instance;
}
}
枚举实现单例模式
public enum Singleton {
INSTANCE;
private InstanceDemo instance;
Singleton() {
instance = new InstanceDemo();
}
public InstanceDemo getInstance() {
return instance;
}
}
参考文献
https://blog.csdn.net/fd2025/article/details/79711198
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html