8

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?

nhahtdh
  • 54,546
  • 15
  • 119
  • 154
a Learner
  • 4,832
  • 10
  • 48
  • 87
  • Enum is a singleton but what are the problems of deserialization of singletons ? – clinton Nov 04 '12 at 15:29
  • 2
    @clinton: if you make a singleton serializable, and don't care about how it's deserialized, you and up with a new instance of your singleton each time it's deserialized, which breaks its singletonness. – JB Nizet Nov 04 '12 at 15:42
  • @JBNizet thanks for the info. I had not looked up that issue regarding singletons before now. Or it may not have struck me as important. – clinton Nov 04 '12 at 16:30

2 Answers2

7

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.

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
1

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?

irreputable
  • 43,835
  • 9
  • 63
  • 92
  • If the singleton is stateless, and the code uses (for example) `if (someVar == SomeSingleton.INSTANCE)`, you really care about its identity. – JB Nizet Nov 04 '12 at 18:11
  • There's no real world use case. Jushua Bloc made this thing up. Usually a singleton should NOT be serializable anyway, using enum to facilitate serialization is just wrong. Also, singleton is an implementation strategy, not something we should publicize at interface. – irreputable Nov 04 '12 at 18:57