Singleton: How should it be used

后端 未结 24 1907
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:

So I have read th

24条回答
  •  伪装坚强ぢ
    2020-11-22 05:04

    Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.

    Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static

    C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.

    Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.

    So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.

提交回复
热议问题