单例模式需要考虑3中特殊情况:
1. clone
2. 序列化,反序列化
3. 反射
解决方法:
1. clone
可以不实现 Cloneable 接口
2. 序列化,反序列化
可以不实现Serializable接口
或者在单例对象中添加:
- private Object readResolve() throws ObjectStreamException {
- // instead of the object we're on,
- // return the class variable INSTANCE
- return INSTANCE;
- }
3. 反射
在私有构造函数中使用标志位控制,如果是第二次调用,则抛出异常