Why is using the singleton pattern discouraged?

Possible Duplicate:
What is so bad about singletons?

I've read in several answers to Stack Overflow questions that using singletons is discouraged and evil. Why is that?


How many times a class is instantiated shouldn't be dictated by the class itself, but from an infrastructure that provides the single instance. Singleton makes it impossible to leave this decision to the infrastructure. It is a reusability issue, which shows up for instance in the unit tests, but also when the infrastructure tries to provide another instance for a certain purpose.

(Eg there is only one database connection. But for importing data from another database, it needs another connection. If the database access service would be a singleton, it is impossible to open another connection.)


Singleton pattern makes unit testing far more difficult, as it introduces global state into an application.

It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialised, eg, by locking.

Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods.

Some have suggested ways to break down the singleton pattern using methods such as reflection in languages such as Java or PHP.


The short answer is they introduce a global-state object in to your code, which breaks your separation of concerns (possibly adding complexity).

Singletons are not without other drawbacks, which you should know about:

http://en.wikipedia.org/wiki/Singleton_pattern#Drawbacks

This article is a bit more verbose:

http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

链接地址: http://www.djcxy.com/p/82156.html

上一篇: 为什么单身人士被认为是不好的做法?

下一篇: 为什么不鼓励使用单例模式?