依赖注入:应该先做哪一个?属性(字段)或依赖?

dependency injection: Which one should be made first? attributes(fields) or dependency?

我是依赖注入的新手,遇到了一些问题。

首先我知道这个:

来自 Christoffer Noring,Pablo Deeleman 的书“学习 Angular - 第二版”:

As our applications grow and evolves, each one of our code entities will internally require instances of other objects, which are better known as dependencies in the world of software engineering. The action of passing such dependencies to the dependent client is known as injection.

然后,在一些教程视频中,讲师说我们想在 Car class 中使用 Tires 服务,所以我们将其注入 Car Class 然后我们将创建一个属性 (轮胎)保存它:

public class Car {

    private Tires tires; 

    public Car(Tires tires){
        this.tires = tires;
    }
}

我不同意这个定义,这让我感到困惑,因为我认为这个定义(教师的定义)与另一个定义形成对比。

关于 DI 的大部分文章(与关于 Angular 相同)告诉我们,由于我们需要 class 中其他 class 对象的实例,我们有一些依赖class。但是在这个定义中,它告诉我们有来自不同 class 的对象,我们想将它注入到您的 class 中,您应该创建一些变量来保存这些值。

我认为混淆的问题是属性创建的时间。我认为首先我们创建属性然后我们有一些依赖性,而不是假设一些 class 作为依赖性然后创建一些属性以将这些值保存在主机 class.(client class)

有人可以解释一下吗?

I think first we create the attribute

我认为您可能将 OOP 概念与注入混淆了。

Car服务class(与OOP无关),需要访问Tires服务 class, 所以 Car 实例期望在构造时注入一个 Tires 实例,它需要保存它以备后用,所以它将引用存储在一个字段(不是属性1)。

当我们决定需要保存注入的引用以备后用时定义(声明,"created")该字段。

我想你可以说我们定义了 ("create") 字段,当我们 意识到 我们需要对 Tire 服务的引用,然后去将其作为依赖项添加到构造函数中,但这只是您编写代码时的语义,即您是在编写需要它的代码之前提前创建依赖项,还是在运行时创建依赖项写代码。

1) 当我们有 getter(和 setter)方法用于外部 class 使用。注入的引用,仅供内部使用,不被视为 class 的 "attribute"。