正确的单例模式有四种实现方式:
- 1.提前初始化(饿汉式)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
- 2.懒汉式(效率低)
public class Singleton {
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 3.双重检查锁定(DCL) + volatile(变异懒汉式)
懒汉式在在多线程的情况下会失效,所以需要改写,添加同步锁。
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
volatile保证变量修改的可见性。
- 4.延迟初始化占位类模式
public class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
}
网友评论