Singleton: How should it be used

后端 未结 24 1885
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:09

    As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.

    Some useful aspects of singletons:

    1. lazy or upfront instantiation
    2. handy for an object which requires setup and/or state

    However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.

    Finally, a factory lends itself to dependency injection technologies like Spring etc.

提交回复
热议问题