Singleton Vs ServiceLocator

后端 未结 2 1661
旧时难觅i
旧时难觅i 2020-12-29 14:59

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

2条回答
  •  借酒劲吻你
    2020-12-29 15:26

    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().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), lower coupling, separation of concerns, etc.

提交回复
热议问题