“Singleton” factories, ok or bad?

后端 未结 6 734
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 08:55

I\'ve a lot of (abstract) factories and they\'re usually implemented as singletons.

Usually for the convenience of not having to pass them through layers who really hav

6条回答
  •  无人共我
    2021-01-31 09:05

    Having a few singletons is pretty typical and not usually problematic--a lot of singletons leads to some irritating code.

    We just went through a situation where we had to test our heavily singleton-laden classes. The problem is that when you are testing class b, and it gets class c (a singleton), you have no way to mock out class c (At least EasyMock wouldn't allow us to replace the static factory method of a singleton class.

    One simple fix is to have "Setters" for all your singletons for testing purposes. Not really recommended.

    One other thing we tried was to have a single class that held all the singletons--a registry. Doing this is getting pretty close to dependency injection which is what you should almost certainly be using.

    Aside from testing, I learned a long time ago that when there is never ever ever going to be more than one instance of a given object; in the next rev they often want two, which makes singletons MUCH better than static classes--at least you can add a parameter to the getter of a singleton and return a second one without too much refactoring (which is again just doing what DI does).

    At any rate, look into DI, you might be really happy.

提交回复
热议问题