“Singleton” factories, ok or bad?

后端 未结 6 725
伪装坚强ぢ
伪装坚强ぢ 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:07

    It really depends on what you're doing and the scope of your application. If it's just a fairly small app and it's never going to grow beyond this, then your current approach may well be fine. There is no universal "best" practice for these things. While I wouldn't recommend using singletons for anything other than stateless leaf methods and/or one-way calls (e.g. logging), dismissing it out of hand 'just because' it's a singleton isn't necessarily the right thing to do.

    For anything other than trivial or prototype code, I personally like to explicitly use inversion of control with constructor injection, as it means all dependencies are accounted for and you don't get any 'surprises'. The compiler won't let you instantiate A without B and B without C. Singletons immediately bury these relationships -- you can instantiate A without B and B without C. When the call from A to B happens, you'll get a null reference exception.

    This is especially annoying when testing, as you have to iteratively work backwards via runtime failures. When you test code, you're using the API just as a fellow coder would do, so it is indicative of the design problems with this approach. Constructor injection ensures this can never happen -- all of the dependencies are stated up front. The downside with constructor injection is that the configuration of your object graph is more complicated. This is mitigated through the use of an IoC container.

    I guess what I'm trying to say is that if you've got to the point where you're considering using some kind of context object and a registry pattern, you may as well have a look at IoC containers. Going to the effort of rolling your own mutt version is probably a waste of time when you can use an established, free product like Autofac.

提交回复
热议问题