Singleton: How should it be used

后端 未结 24 2227
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:11

    One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.

    Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.

    Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.

    It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.

提交回复
热议问题