Most common examples of misuse of singleton class

后端 未结 11 927
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 00:19

When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of \'singletonitis\' t

相关标签:
11条回答
  • 2020-12-16 01:13

    I'm guilty of a big one a few years back (thankfully I've learned my lession since then).

    What happened is that I came on board a desktop app project that had converted to .Net from VB6, and was a real mess. Things like 40-page (printed) functions and no real class structure. I built a class to encapsulate access to the database. Not a real data tier (yet), just a base class that a real data tier could use. Somewhere I got the bright idea to make this class a singleton. It worked okay for a year or so, and then we needed to build a web interface for the app as well. The singleton ended up being a huge bottleneck for the database, since all web users had to share the same connection. Again... lesson learned.

    Looking back, it probably actually was the right choice for a short while, since it forced the other developers to be more disciplined about using it and made them aware of scoping issues not previously a problem in the VB6 world. But I should have changed it back after a few weeks before we had too much built up around it.

    0 讨论(0)
  • 2020-12-16 01:16

    I try to have only one singleton - an inversion of control / service locator object.

    IService service = IoC.GetImplementationOf<IService>();
    
    0 讨论(0)
  • 2020-12-16 01:18

    Here is a rant by my friend Alex Miller... It does not exactly enumerate "when you should NOT use a singleton" but it is a comprehensive, excellent post and argues that one should only use a singleton in rare instances, if at all.

    0 讨论(0)
  • 2020-12-16 01:19

    Well singletons for the most part are just making things static anyway. So you're either in effect making data global, and we all know global variables are bad or you're writing static methods and that's not very OO now is it?

    Here is a more detailed rant on why singletons are bad, by Steve Yegge. Basically you shouldn't use singletons in almost all cases, you can't really know that it's never going to be needed in more than one place.

    0 讨论(0)
  • 2020-12-16 01:21

    I know many have answered with "when you have more than one", etc.

    Since the original poster wanted a list of cases when you shouldn't use Singletons (rather than the top reason), I'll chime in with:

    Whenever you're using it because you're not allowed to use a global!

    The number of times I've had a junior engineer who has used a Singleton because they knew that I didn't accept globals in code-reviews. They often seem shocked when I point out that all they did was replace a global with a Singleton pattern and they still just have a global!

    0 讨论(0)
提交回复
热议问题