Possible Duplicate:
What is so bad about singletons?
I've read in several answers to Stack Overflow questions tha开发者_JAVA技巧t 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.
(E.g. 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, e.g., 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
The reason is probably that they're basically global variables. Even so, they're used quite extensively in some environments. For example, in long running web services. In Java with the Spring Framework for example, the default bean type is a singleton, and typically controllers, services, and DAO objects are singleton (in the sense that the framework only instantiates one instance). They do NOT require locking and are also thread safe, because by convention they contain no state. Typically a request context is passed in, and the controller/service/DAO operates on that.
精彩评论