Singleton class vs. class with static member

后端 未结 2 992
星月不相逢
星月不相逢 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: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).

提交回复
热议问题