目录
1.普通单例实现方式(非线程安全)
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (Objects.isNull(instance)) {
instance = new Singleton();
}
return instance;
}
}
2.在1代码实现的基础上增加线程安全同步处理(线程安全)
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (Objects.isNull(instance)) {
instance = new Singleton();
}
return instance;
}
}
3.静态变量初始化方式实现(线程安全)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
4.静态代码块实现单例(线程安全)
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
5.静态内部类方式实现单例(线程安全)
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6.使用枚举实现单例(线程安全)
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
7.双锁方式保证线程安全的单例设计模式实现(线程安全)
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}