Can anyone provide an example of a singleton pattern and explain why they are necessary?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Before going the singleton route, reconsider. Do you really need a singleton? If you’re asking for scenarios when you need to implement singletons, it’s because the need for them didn’t really express. You’re better off not introducing singletons in your code base just because it feels cool to follow design patterns.
Clean Code Talks – Global State and Singletons
Once Is Not Enough
Performant Singletons
However, what’s really worth knowing is Dependency Injection.
Now if you really want to implement singletons in Java, I would recommend Joshua Bloch’s “Effective Java” way of implementing them:
The JLS guarantees the JVM will not initialize instance until someone calls
getInstance();Final note, the Double Checked Locking Pattern is broken in Java up to Java 5. The Java 5 memory model makes the DCL pattern thread safe but it makes it slower than the
SingletonHolderclass method while the original intent was performance optimization.EDIT: As @Luno pointed out, since the second edition of the book, the preferred way is: