单例模式
单例模式:类只能创建一个实例,并提供对实例的静态访问方法。
要点:
- 私有构造器
- 静态私有变量
- 声明可全局访问的公有静态方法
饿汉式
饿汉式:静态私有变量默认初始化(线程安全)。
public class Singleton {
private Singleton() {}
private static Singleton singleton = new Singleton();
public static Singleton getInstance() {
return singleton;
}
}
懒汉式(非线程安全)
懒汉式:静态私有变量默认不初始化(非线程安全)。
public class Singleton {
private Singleton() {}
private static Singleton singleton;
public static Singleton getInstance() {
if (singleton == null) singleton = new Singleton();
return singleton;
}
}
懒汉式-synchronized(线程安全)
线程安全,性能很差。
public class Singleton {
private Singleton() {}
private static Singleton singleton;
public static synchronized Singleton getInstance() {
if (singleton == null) singleton = new Singleton();
return singleton;
}
}
// 或
public class Singleton {
private Singleton() {}
private static Singleton singleton;
public static Singleton getInstance() {
synchronized (Singleton.class) {
if (singleton == null) singleton = new Singleton();
}
return singleton;
}
}
懒汉式-双重检测(double check)(线程安全)
线程安全,比synchronized性能好。
public class Singleton {
private Singleton() {}
private static Singleton singleton;
public static Singleton getInstance() {
// 第一次检测
if (singleton == null) {
synchronized (Singleton.class) {
// 第二次检测
if (singleton == null) singleton = new Singleton();
}
}
return singleton;
}
}
静态内部类(线程安全)
线程安全,性能很好。
public class Singleton {
private Singleton() {}
private static class SingletonHoler {
private static Singleton singleton = new Singleton();
}
public static Singleton getInstance() {
return SingletonHoler.singleton;
}
}
枚举(线程安全)
线程安全,性能很好。
public enum Singleton {
INSTANCE
}