[英]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 {
}
In my code I am accepting object of class through reference of class B not by parent interface A. 在我的代码中,我通过类B的引用而不是通过父接口A接受类的对象。
Is my code loosely or tightly coupled? 我的代码是松散耦合还是紧密耦合?
Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns. 松耦合是通过促进单一责任和关注点分离的设计实现的。
using the reference of parent class or interface make code more flexible to adopt any child class's object but how does it promotes single-responsibility. 使用父类或接口的引用可使代码更灵活地采用任何子类的对象,但是它如何促进单一职责。
Is loose coupling can be achieved by any other manner rather than using parent class reference variable, in any case not specifically in mine code? 是否可以通过任何其他方式而不是使用父类引用变量来实现松散耦合,无论如何在矿井代码中并非如此?
This feels homeworky, but here is my answer. 这感觉很家庭作业,但这是我的答案。
The code is tightly coupled because the constructor for C
depends upon B
instead of the interface A
. 该代码紧密耦合,因为C
的构造函数依赖于B
而不是接口A
If you wanted to decouple C
from B
, you would accept an instance of A
instead of B
. 如果要从B
解耦C
,则可以接受A
的实例,而不是B
的实例。
Loosely Coupled Code 松耦合代码
class C {
A a;
C(A a) {
this.a = a;
}
}
Ans1: Ans1:
Tight coupling is when a group of classes are highly dependent on one another. 紧密耦合是一组类彼此高度依赖时。
Your code is tight coupled because: 您的代码紧密耦合,因为:
Because constructor for C depends upon B, and you are storing object of B in type A. 因为C的构造函数取决于B,并且您将B的对象存储在类型A中。
Ans2: Ans2:
Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns. 松耦合是通过促进单一责任和关注点分离的设计实现的。
Interfaces are a powerful tool to use for decoupling. 接口是用于解耦的强大工具。 Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface. 类可以通过接口而不是其他具体类进行通信,并且任何类都可以通过实现接口而位于通信的另一端。
Example: 例:
class C {
A a;
C(A b) { // use interface A rather Class B
a = b;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.