Why use singleton instead of static class?

前端 未结 7 726
迷失自我
迷失自我 2020-12-08 04:02

When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that\'s not actually needed, but I\'m sure

7条回答
  •  温柔的废话
    2020-12-08 04:37

    Singletons are often preferred to global variables because:

    • They don't pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
    • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

    Source

    EDIT:

    One cool use of the singleton is, when combined with the factory method, can be used to create the Flyweight pattern. This is when you create a new object, the Factory (instead of creating a new object) first checks to see a singleton of that object is already made, if it is, it just returns that object, if not, it creates a new singleton and returns that, keeping track of the singletons it creates. Flyweights work because of the immutability of the singleton.

提交回复
热议问题