gpt4 book ai didi

dependency-injection - 关联注入(inject)还是依赖注入(inject)?

转载 作者:行者123 更新时间:2023-12-04 08:21:44 28 4
gpt4 key购买 nike

我正在研究依赖注入(inject)模式。我看过很多例子,其中一个典型的例子是使用 XxxService/XxxRepository 作为例子。但是在我看来,按照UML的概念,类XxxRepository应该是类XxxService的一个关联。为什么不调用这种情况关联注入(inject) ,但仍然依赖注入(inject)?:)

谢谢!

2018 年 1 月 26 日更新

我目前认为dependency injection的概念适合这个问题中描述的情况。因为协会 只是一个特殊的依赖 在 UML 中。

Please refer to this article ,马丁·福勒说:

"a dependency exists between two elements if changes to the definition of one element (the supplier) may cause changes to the other (the client)". This is a very vague and general relationship, which is why the UML has a host of stereotypes for different forms of dependency.





Associations also imply dependency, if there is an association between two classes, there is also a dependency.



所以我现在不能接受任何答案。或者这个问题可能不是一个好问题,因为每个开发人员都有自己的观点。我正在认真考虑结束这个问题。

最佳答案

首先 : 我想澄清一些关于 的提示。依赖注入(inject) .

在依赖注入(inject)中(参见 reference(第 4 段)):

  • The client does not need to know how to construct the services.
  • The client does not need to know which actual services it is using.
  • The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services.


当我们使用如下代码的依赖注入(inject)时:
class A {
@Inject
private IB b;

//...
}

我们实际上并不知道,哪个类的哪个对象(实现了 IB )被注入(inject)到 b 中。 .

也许注入(inject)的类在运行时发生了变化,也许是因为一些手动或自动处理的配置而发生了变化。也许它会随着时间的推移而动态变化等。

所以,我们不能使用类 A 之间的关联。和其他类(哪个类?或哪个对象?)

因此 , 类 A 之间只有依赖关系和界面 IB .

在小型项目中,也许我们只有一个 IB 的实现。在我们的项目中。或者我们没有任何机制来进行动态注入(inject)。在这种情况下,可以使用关联。但是,在这种情况下,不需要依赖注入(inject)。

要从 Martin Fowler 那里找到好的解释和好的例子,请参阅 reference 2 .

关于dependency-injection - 关联注入(inject)还是依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117639/

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