Enums, Singletons and Deserialization
Enums are considered best way for singletons and one of reasons for this is that it implicitly inherits Serializable
.
But how enums prevents de-serialization problem of singletons?
The serialization mechanism handles them in a special, specific way. But traditional singletons can be deserialized fine by defining a readResolve()
method that returns the unique instance. See http://www.oodesign.com/singleton-pattern.html for an example.
Serialization as an argument for using enum for singleton is nonsense.
If the enum singleton is stateful, the state is lost during serialization/deserialization.
If the singleton is stateless, who cares about its identity?
链接地址: http://www.djcxy.com/p/78836.html上一篇: 静态变量初始化顺序
下一篇: 枚举,单例和反序列化