What are the advantages and disadvantages of using a Service Locator versus a singleton? I've read that singletons are bad but I'm wondering if s Service Locator would be generally a better way of doing things.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Both approaches are bad in that it's not obvious from class contract what are its' dependencies. That is,
private void foo()
{
var x = SomeSingleton.Instance.GetX();
var y = ServiceLocator.GetService<IProvider>().GetY();
}
has references to SomeSingleton
and IProvider
buried deep somewhere inside.
However, compared to pure singleton approach, service locators are generally much better in that they allow for simpler centralized configuration, lifetime management, etc. They also allow for better testability (you can always mock calls to GetService<T>
), lower coupling, separation of concerns, etc.
回答2:
if testability is a concern, using service locator is much better then pure singletons.