Purpose of singletons in programming

后端 未结 9 1711
傲寒
傲寒 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:25

    Like others have said:

    • Singletons are global variables by another name.
    • Singletons are usually a bad idea.
    • Singletons could be replaced by "monostate" classes - classes that have apparently normal construction / destruction semantics but all share the same state.

    Note that in my opinion "static classes" are usually also a bad idea, a hackish workaround for a language that does not allow free functions, or for sharing state between a bunch of functions without wanting to pass that state as a parameter.

    In my experience nearly all designs with singletons or static classes can be turned into something better, more easily understood and more flexible by getting rid of those constructs.

    Edit: By request, why most singletons are global variables by another name.

    In most of the languages I know, most singleton classes are accessed through a static member function of that class. The single instance is available to all code that has access to the definition of the singleton class. This is a global variable - all code that includes the class could be making modifications to the single instance of your singleton.
    If you do not use the static member function (or some static factory method which has the same implications), but instead pass the singleton object to all clients that need it, then you would have no need for the singleton pattern, just pass the same object to all clients.

提交回复
热议问题