Simplified Singleton pattern in Java
design-patterns, java, singleton
Solution
The recommended (by Effective Java 2nd ed) way is to do the "enum singleton pattern":
enum MyClass {
INSTANCE;
// rest of singleton goes here
}
The key insight here is that enum values are single-instance, just like singleton. So, by making a one-value enum, you have just made yourself a singleton. The beauty of this approach is that it's completely thread-safe, and it's also safe against any kinds of loopholes that would allow people to create other instances.
Problem
The default way to implement singleton pattern is: ``` class MyClass { private static MyClass instance; public static MyClass getInstance() { if (instance == null) { instance = new MyClass(); } return instance; } } ``` In an old project, I've tried to simplify the things writing: ``` class MyClass { private static final MyClass instance = new MyClass(); public static MyClass getInstance() { return instance; } } ``` But it sometimes fail. I just never knew why, and I did the default way. Making a SSCCE to post here today, I've realized the code works. So, I would like to know opinions.. Is this a aleatory fail code? Is there any chance of the second approach return null? Am I going crazy? -- Although I don't know if is the right answer for every case, it's a really interesting answer by @Alfred: I also would like to point out that singletons are testing nightmare and that according to the big guys you should use google's dependency injection framework.