1.双重检查锁定(double checked locking)
public class Singleton implements Serializable{
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
private volatile static Singleton instance = null;
/* 私有构造方法,防止被实例化 */
private Singleton() {}
/* 静态工厂方法,创建实例 */
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
private Object readResolve() {
return instance;
}
}
2.静态工厂
private static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
或者
private static final Singleton uniqueInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return uniqueInstance;
}
3.静态内部类
- public class Singleton {
- private static class LazyHolder {
- private static final Singleton INSTANCE = new Singleton();
- }
- private Singleton (){}
- public static final Singleton getInstance() {
- return LazyHolder.INSTANCE;
- }
- }
4.枚举
public enum Singleton {
INSTANCE;
}
使用枚举的原因:
1.枚举单例可以自己处理序列化
2.保证只有一个实例(即使使用反射也无法多次实例化一个枚举量)
3.线程安全