Singleton design pattern is to be used when we want to ensure that only 1 instance of the class should be created. For e.g if we have only 1 liscence for something. Is the below the right way to implement it ?
Monica Shiralkar wrote:. . . whether it will have any benefit over the one I originally posted. . . .
No, it hasn't. It isn't thead‑safe. I think the only good way to create a singleton is what Paul showed you.
There is doubt about whether a singleton is a pattern or an anti‑pattern.
Campbell Ritchie wrote:There is doubt about whether a singleton is a pattern or an anti‑pattern.
It can be a pattern or anti-pattern; it just depends on how you apply it. That said, many applications of Singleton are anti-patterns because they cause more problems than they solve.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Monica Shiralkar wrote:And how would rest of the code be?
That is the bare minimum you need to implement an enum singleton in Java. Obviously, if your singleton has some behavior that it needs to exhibit, the rest of the class would be whatever is needed to implement that behavior.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Thanks. So this means that code which I had originally pasted is required only for pre java 5 compiler and from java 5 onwards the code is a very short one using Enum as shown.