Ways of Dependency Injection

后端 未结 2 953
野性不改
野性不改 2021-01-15 08:58

Can the Factory Patterns (Factory Method,Simple Factory Method and Abstract Factory) or Service Locator Pattern way of fetching the dependency be called Dependency Injection

2条回答
  •  滥情空心
    2021-01-15 09:08

    No, they can't.

    Dependency injection is a pattern that implements IoC or inversion of control. It implies, that classes should not be tightly coupled to each other and should not know about where to fetch their dependency.

    Inversion of control principle is often expressed as "Don't call us, we'll call you" - in this case the classes, managed by IoC container shouldn't know anything about their dependencies and how to fetch them. Factory patterns and service locator implies, that the using class actually knows about the way to fetch that dependency.

    UPDATE

    Let me also cite Martin Fowler:

    The fundamental choice is between Service Locator and Dependency Injection. The first point is that both implementations provide the fundamental decoupling that's missing in the naive example - in both cases application code is independent of the concrete implementation of the service interface. The important difference between the two patterns is about how that implementation is provided to the application class. With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control.

    http://martinfowler.com/articles/injection.html

提交回复
热议问题