谁能向我解释这是什么意思?尤其是粗线。
要使单例类可序列化,仅仅添加到它的声明是不够
implements Serializable
的。要维护单例保证,您必须声明所有实例字段transient
并提供readResolve()
方法。否则,每次反序列化序列化实例时,都会创建一个新实例,在我们的示例中,这会导致虚假的 Elvis 目击事件。为了防止这种情况,将此readResolve()
方法添加到Elvis
类中:// 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,Item 3