gpt4 book ai didi

jakarta-ee - 何时使用依赖注入(inject)与服务定位器

转载 作者:行者123 更新时间:2023-12-04 19:13:54 25 4
gpt4 key购买 nike

什么时候使用依赖注入(inject)?使用依赖注入(inject)有什么压倒性的好处吗?

最佳答案

Fowler 在他的 Inversion of Control Containers and the Dependency Injection pattern Heading 中对两者进行了很好的比较。 .在他的总结性想法中,他说

Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.



您可以在 here中找到更多的观点和比较

对于 DI:
  • 更容易确定组件具有哪些依赖项 - 查看
    构造函数。
  • 组件不依赖服务定位器,所以
    如果该组件与不同的组件一起使用,则没有问题
    框架。
  • DI 可能会使测试更容易,但它是一个很好的服务定位器
    机制将使 stub 同样可行

  • 反对 DI:
  • 更难调试和理解。
  • 组件一旦配置就不能从注入(inject)器请求额外的服务。
  • 关于jakarta-ee - 何时使用依赖注入(inject)与服务定位器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12205826/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com