Purpose of singletons in programming

后端 未结 9 1592
傲寒
傲寒 2020-12-08 01:49

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever crea

相关标签:
9条回答
  • 2020-12-08 02:42

    why you would wan't to

    I wouldn't because singletons usually are very bad way to solve your problems. My recommendation to you is to avoid them completely.

    The main reasons are:

    • Singletons mostly represent global state (which is evil).
    • Correct dependency injection becomes impossible.

    I suggest you read the rest (including thorough explanations) in this Google employee's blog:

    • http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
    • http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/
    • http://misko.hevery.com/2008/08/25/root-cause-of-singletons/
    • http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/
    0 讨论(0)
  • 2020-12-08 02:44

    In addition to the other answers I'd have to say that Singletons can help you when you want a static class, but can't have it, because due to the design of your application it will be inheriting an instantiable class.

    0 讨论(0)
  • 2020-12-08 02:45

    Singletons are mostly useful when you want an interface to a singleton service, but you don't know until runtime which concrete class will be instantiated.

    For instance, you might want to declare a central logging service, but only decide at runtime whether to hook in a file logger, stub logger, database logger, or message-queue logger.

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