如何实现一个单例
1、构造器需要私有化
2、提供一个私有的静态变量
3、暴露一个公共的获取单例对象的接口
需要考虑的两个问题
1、是否支持懒加载
2、是否线程安全
1、饿汉式
java
public class EagerSingleton {
private static final EagerSingleton INSTANCE = new EagerSingleton();
private EagerSingleton(){}
public EagerSingleton getInstance(){
return INSTANCE;
}
}
不支持懒加载
线程安全
2、懒汉式
java
public class LazySingleton {
private static LazySingleton INSTANCE;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
支持懒加载
线程不安全
java
public class LazySingleton {
private static LazySingleton INSTANCE;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
支持懒加载
线程安全
3、双重检查锁
java
public class DoubleCheckSingleton {
private static DoubleCheckSingleton INSTANCE;
private DoubleCheckSingleton() {
}
public DoubleCheckSingleton getInstance() {
if (INSTANCE == null) {
synchronized (DoubleCheckSingleton.class) {
if (INSTANCE == null) {
INSTANCE = new DoubleCheckSingleton();
}
}
}
return INSTANCE;
}
}
支持懒加载
线程安全
4、静态内部类
java
public class InnerSingleton {
private InnerSingleton() {
}
public static InnerSingleton getInstance() {
return Singleton.INSTANCE;
}
private static class Singleton {
private static final InnerSingleton INSTANCE = new InnerSingleton();
}
}
支持懒加载
线程安全
5、枚举
java
public enum EnumSingleton {
INSTANCE;
}
支持懒加载
线程安全