如何处理Singleton以及序列化 [英] How to deal with Singleton along with Serialization
问题描述
考虑我有一个Singleton类定义如下。
Consider I have a Singleton class defined as follows.
public class MySingleton implements Serializable{
private static MySingleton myInstance;
private MySingleton(){
}
static{
myInstance =new MySingleton();
}
public static MySingleton getInstance(){
return MySingleton.myInstance;
}
}
根据我的上述定义满足a的要求Singleton。添加的唯一附加行为是该类实现可序列化接口。
The above definition according to me satisfies the requirements of a Singleton.The only additional behaviour added is that the class implements serializable interface.
如果另一个类X获取单个实例并将其写入文件,稍后point反序列化它以获得另一个实例,我们将有两个实例违反Singleton原则。
If another class X get the instance of the single and writes it to a file and at a later point deserializes it to obtain another instance we would have two instances which is against the Singleton principle.
我如何避免这种情况,或者我在上面的定义本身是错误的。
How can I avoid this or am I wrong in above definition itself.
推荐答案
最好的方法是使用枚举单例模式:
The best way to do this is to use the enum singleton pattern:
public enum MySingleton {
INSTANCE;
}
这保证了对象的单一性并为你提供了可串行化的功能。一种总是得到相同实例的方式。
This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.
更一般地说,你可以提供一个 readResolve()
方法所以:
More generally, you can provide a readResolve()
method like so:
protected Object readResolve() {
return myInstance;
}
这篇关于如何处理Singleton以及序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!