Too much singletons in the project - is it a bad practice?

后端 未结 4 1652
我在风中等你
我在风中等你 2020-12-19 16:46

In almost every project I create a few classes which implement Singleton pattern. For example, data manager - if there\'s some work with file system, data loader - if an app

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 17:12

    Since TDD took its place programmers learned that testing singletons is a pain and started avoiding it. The same effect can be achieved by injecting needed classes/resources such as connection manager, resource manager, etc. Going this way, in the test environment these classes can simply be mocked, injected and covered with test.

    On the other hand, in some cases only using singleton seems the right way - for ensuring that only one instance exists. I.e. it is useful for connection pools for it guarantees that one and only one instance exists at the time and there will be no leaks. (Note: not all implementation of singleton pattern can really provide this. In Java the right way would be using enum - for the language itself ensures its uniqueness.)

    In summary, my answer is yes, using too much singletons is bad. Consider using DI principle instead.

提交回复
热议问题