What is so bad about singletons?

The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.

Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?

Please support your answers with "facts, references, or specific expertise"


Paraphrased from Brian Button:

  • They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  • They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  • They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  • They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.


  • Singletons solve one (and only one) problem.

    Resource Contention.

    If you have some resource that

    ( 1 ) can only have a single instance, and

    ( 2 ) you need to manage that single instance,

    you need a singleton .

    There aren't many examples. A log file is the big one. You don't want to just abandon a single log file. You want to flush, sync and close it properly. This is an example of a single shared resource that has to be managed.

    It's rare that you need a singleton. The reason they're bad is that they feel like a global and they're a fully paid up member of the GoF Design Patterns book.

    When you think you need a global, you're probably making a terrible design mistake.


    Some coding snobs look down on them as just a glorified global. In the same way that many people hate the goto statement there are others that hate the idea of ever using a global. I have seen several developers go to extraordinary lengths to avoid a global because they considered using one as an admission of failure. Strange but true.

    In practice the Singleton pattern is just a programming technique that is a useful part of your toolkit of concepts. From time to time you might find it is the ideal solution and so use it. But using it just so you can boast about using a design pattern is just as stupid as refusing to ever use it because it is just a global.

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

    上一篇: 在PHP5中创建Singleton设计模式

    下一篇: 单身人士有什么不好?