Singleton pattern (Bill Pugh’s solution)

I think Mr Pugh’s version is held in high regard because it only performs the instantiation of the singleton when getInstance() is called i.e. not when the class (the class holding the getInstance method) is loaded. If your singleton construction does something costly then this may be an advantage for you. If you’re like the majority of the world whose singletons are just to avoid static methods (and you haven’t moved onto dependency injection frameworks), then I would not lose any sleep over it.

As the article states, Mr Pugh’s method is lazier than the static instance variable – but in reality if the Singleton class gets loaded you’re going to be calling the getInstance method anyhow. So as a computer science exercise it’s useful, but in the real world its benefits are debatable.

p.s. I don’t care much for Mr Bloch’s example here as to use an enum would be to say My Singleton IS-A enum, which doesn’t sound right to me (especially from someone who, rightly, says never implement an interface just to get the constants)

Leave a Comment