Is Monostate the good cousin of the evil Singleton?

前端 未结 8 1653
梦如初夏
梦如初夏 2021-02-08 23:21

Singleton is definitely one of the most misused and abused patterns out there. Many of us have been infected with Singletonitis at one point or another. Curiously, its close c

相关标签:
8条回答
  • 2021-02-08 23:54

    Here is an excerpt from page 127 of Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.

    Use the Singleton pattern when

    • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
    • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code

    Does it really make singletons evil just because they are misused and misunderstood?

    0 讨论(0)
  • 2021-02-08 23:56

    Why are you assuming that people would discourage the use of Singletons? Making sweeping generalizations about Singletons is like making sweeping generalizations about gotos, global variables and so on. There is a place for all of them. None of these things are "evil", and their misuse doesn't make them bad to use, it just means they need to be used properly.

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