Singleton class vs. class with static member

后端 未结 2 996
星月不相逢
星月不相逢 2021-02-02 01:54

Despite the many threads on that topic, I am still unclear as to when to choose which approach. I am hoping that by discussing a specific example, I will finally \"get it.\"

相关标签:
2条回答
  • 2021-02-02 02:49

    Singleton is a design pattern , Static is a C# keyword to make objects global.

    Singleton = Static + Thread safety + Lazy loading + Iterator pattern

    This is a nice presentation where the difference is explained with a sample code. https://www.youtube.com/watch?v=csQdTkEdhME

    0 讨论(0)
  • 2021-02-02 02:55

    The main differences are simple things like:

    • with a singleton you can pass around the object for delegates and callbacks
    • with a singleton you can implement interfaces and derive it
    • with a singleton you can use a factory pattern to build up your instance

    If you don't need any of them, as with global functionality that must be accessed all around your code then you can go with static methods.

    I personally prefer using static methods unless I have an explicit reason to use a singleton instance (such as having a common interface but different implementations).

    Mind the fact that refactoring static methods to a singleton instance is quite a straightforward process so if you ever find the need for the latter you will refactor it easily (then you have the C preprocessor, a single #define would be almost enough).

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