Are there any downsides to the singleton pattern? [duplicate]

别说谁变了你拦得住时间么 提交于 2020-01-06 07:20:31

问题


Possible Duplicates:
What is so bad about Singletons
Problems with Singleton Pattern

Are there any downsides to the singleton pattern? I heard this was an interview question and i am coming up short on what was meant.

imho, it's about the usage and nothing in the pattern itself is problematic


回答1:


From Wikipedia:

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.




回答2:


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.



回答3:


  1. Not testable or at least it's difficult
  2. Hard to find dependent classes
  3. Does not allow subclassing
  4. ...


来源:https://stackoverflow.com/questions/2343721/are-there-any-downsides-to-the-singleton-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!