ls 松散耦合可以通过任何其他方式而不是使用 parent class 引用变量来实现,一般来说不是专门在我的代码中?

ls loose coupling can be achieved by any other manner rather than using parent class reference variable, in general not specifically in mine code?

Tight coupling is when a group of classes are highly dependent on one another.

class C {
    A a;

    C(B b) {
      a = b;
    }
}

Interface A {
}

class B implements A {
}

在我的代码中,我通过引用 class B 而不是父接口 A 来接受 class 的对象。

  1. 我的代码是松耦合还是紧耦合?

    Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

  2. 使用父 class 的引用或接口使代码更灵活地采用任何子 class 的对象,但它如何促进单一责任。

  3. 是否可以通过任何其他方式而不是使用父 class 引用变量来实现松散耦合,无论如何在我的代码中没有具体说明?

这感觉有点繁琐,但这是我的答案。

代码紧密耦合,因为 C 的构造函数依赖于 B 而不是接口 A。如果您想将 CB 分离,您将接受 A 的实例而不是 B.

松耦合代码

class C {
    A a;

    C(A a) {
      this.a = a;
    }
}

答案1:

Tight coupling is when a group of classes are highly dependent on one another.

您的代码是紧耦合的,因为:

因为 C 的构造函数依赖于 B,而您正在以 A 类型存储 B 的对象。

答案2:

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

接口是用于解耦的强大工具。 类 可以通过接口而不是其他具体的 classes 进行通信,并且任何 class 都可以通过实现接口简单地位于该通信的另一端。

示例:

class C {
    A a;

    C(A b) { // use interface A rather Class B
      a = b;
    }
}