用枚举实现单例,除了线程同步之外貌似没有其他什么作用吧?是我的写法不对吗?
package thread;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* 线程安全、防反射、防反序列化的单例模式
*
* @author LYW
* @date 2019/3/21
* @since JDK 1.8
*/
public class SingletonDemo implements Serializable {
private static final long serialVersionUID = 8371689835544598243L;
private SingletonDemo() {
if (Singleton.INSTANCE != null) {
throw new RuntimeException("单例模式被侵犯!");
}
}
public static SingletonDemo getInstance() {
return Singleton.INSTANCE.getInstance();
}
/**
* 防反序列化,在反序列化获取对象时,直接返回当前对象
*
* @return
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException {
return Singleton.INSTANCE.getInstance();
}
private enum Singleton {
INSTANCE();
private SingletonDemo instance;
Singleton() {
instance = new SingletonDemo();
}
public SingletonDemo getInstance() {
return instance;
}
}
}