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
  • 55,989
  • 15
  • 126
  • 162
a Learner
  • 4,944
  • 10
  • 53
  • 89
  • 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
  • 678,734
  • 91
  • 1,224
  • 1,255
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
  • 44,725
  • 9
  • 65
  • 93
  • 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