Are there any downsides to the singleton pattern? [duplicate]
Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.
Personally, since I've started using Spring to auto-wire my application I've never had the need to write a singleton.
That's a very generic question, it really depends on your use cases. I'd cite the following:
- You always need a mutex (or synchronized block) to protect the initial getInstance() call, which can be problematic in some cases.
- It is a hack to hide the fact that you are creating a global variable, and global variables are generally bad. However, there are many cases where the simplicity that they bring is appreciable, but pay attention not to abuse them.
- Not testable or at least it's difficult
- Hard to find dependent classes
- Does not allow subclassing