单例模式实现方式 |
线程安全 |
延迟加载 |
反射安全 |
序列号安全 |
饿汉模式 |
√ |
× |
× |
× |
懒汉模式(非空判断) |
× |
√ |
× |
× |
懒汉模式(方法加锁) |
√ |
√ |
× |
× |
懒汉模式(双重检查锁) |
√ |
√ |
× |
× |
静态内部类 |
√ |
√ |
× |
× |
枚举 |
√ |
√ |
√ |
√ |
/**
* 饿汉
* @author bell.zhouxiaobing
*
*/
public class Singleton implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton() {
}
private static Singleton SINGLETON = new Singleton();
public static Singleton getInstance() {
return SINGLETON;
}
}
/**
* 懒汉-非线程安全
* @author bell.zhouxiaobing
*
*/
public class Singleton implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton() {
}
private static Singleton SINGLETON;
public static Singleton getInstance() {
if (SINGLETON == null) {
SINGLETON = new Singleton();
}
return SINGLETON;
}
}
/**
* 懒汉-线程安全
* @author bell.zhouxiaobing
*
*/
public class Singleton implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton() {
}
private static Singleton SINGLETON;
public static synchronized Singleton getInstance() {
if (SINGLETON == null) {
SINGLETON = new Singleton();
}
return SINGLETON;
}
}
/**
* 懒汉-双重校验锁
* @author bell.zhouxiaobing
*
*/
public class Singleton implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton() {
}
private volatile static Singleton SINGLETON;// 内存可见性
public static Singleton getInstance() {
if (SINGLETON == null) {
synchronized (Singleton.class) {//synchronized 原子性 有序性 内存可见性
if (SINGLETON == null) {
SINGLETON = new Singleton();
}
}
}
return SINGLETON;
}
}
/**
* 静态内部类
* @author bell.zhouxiaobing
*
*/
public class Singleton implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Singleton() {
}
private static class Inner{
private static Singleton SINGLETON = new Singleton();
}
public static Singleton getInstance() {
return Inner.SINGLETON;
}
}
/**
* 枚举
* @author bell.zhouxiaobing
*
*/
public enum Singleton implements Serializable{
SINGLETON;
// 可以防止使用 反射 来生成新对象
// 可以防止使用 序列化 方式生成新对象
}
public class SingletonTest {
public static void main(String[] args) throws Exception {
Singleton instance = Singleton.getInstance();
System.out.println(instance);
// 拿到所有的构造函数,包括非public的
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
// 使用空构造函数new一个实例。即使它是private的~~~
Singleton sReflection = constructor.newInstance();
System.out.println(sReflection);
System.out.println(instance == sReflection);
}
}
public class SingletonSerializableTest {
// Singleton类需要实现Serializable序列化接口
public static void main(String[] args) throws Exception {
Singleton s = Singleton.getInstance();
byte[] serialize = SerializationUtils.serialize(s);
Object deserialize = SerializationUtils.deserialize(serialize);
System.out.println(s);
System.out.println(deserialize);
System.out.println(s == deserialize);
}
}