a Learner
a Learner

Reputation: 5042

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?

Upvotes: 8

Views: 1737

Answers (2)

irreputable
irreputable

Reputation: 45443

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?

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 7

Related Questions