谁能给我解释一下这是什么意思?特别是粗线。
To make a singleton class serializable, it is not sufficient merely to add
implements Serializable
to its declaration. To maintain the singleton guarantee, you have to declare all instance fieldstransient
and provide areadResolve()
method. Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading, in the case of our example, to spurious Elvis sightings. To prevent this, add thisreadResolve()
method to theElvis
class:// Singleton with static factory public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public static Elvis getInstance() { return INSTANCE; } public void leaveTheBuilding() { ... } } // readResolve method to preserve singleton property private Object readResolve() { // Return the one true Elvis and let the garbage collector // take care of the Elvis impersonator. return INSTANCE; }
仅供引用:这些行来自 Effective Java Book,第 3 项
最佳答案
readResolve
方法在 ObjectInputStream
从流中读取一个对象并准备将其返回给调用者时被调用。 ObjectInputStream
检查对象的类是否定义了 readResolve
方法。如果定义了该方法,则调用readResolve
方法让流中的对象指定要返回的对象。
在单例情况下,我们将返回在类加载时创建的相同实例,并且不会返回任何新实例。所以保持单例。
关于java - 需要解释,为什么向 Singleton 类添加 implements Serializable 是不够的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440511/