在面向对象范式中,有人能准确地描述松耦合和紧耦合之间的区别吗?
当前回答
这是关于类对其他类的依赖率,在松散耦合时很低,而在紧密耦合时很高。在面向服务的体系结构中,服务之间是松散耦合的,不同的类之间的依赖是有意的
其他回答
当两个对象松散耦合时,它们可以相互作用,但知之甚少 对方。
松散耦合设计允许我们构建能够处理变更的灵活的OO系统。
观察者设计模式是一个让类松散耦合的好例子,你可以在维基百科上看到它。
松耦合是在不提供依赖关系的所有信息的情况下,间接地给出类所需要的依赖关系的过程。E在from的接口中),以防紧耦合,你直接给出依赖关系,这不是编码的好方法。
紧密耦合意味着一个类依赖于另一个类。 松耦合意味着一个类依赖于接口而不是类。
在紧密耦合中,方法中声明了硬编码的依赖项。 在松耦合中,我们必须在运行时向外部传递依赖项,而不是硬编码。(松散耦合系统使用接口来减少与类的依赖。)
例如,我们有一个系统可以以两种或多种方式发送输出,如JSON输出、CSV输出等。
紧耦合的
public interface OutputGenerator {
public void generateOutput();
}
public class CSVOutputGenerator implements OutputGenerator {
public void generateOutput() {
System.out.println("CSV Output Generator");
}
}
public class JSONOutputGenerator implements OutputGenerator {
public void generateOutput() {
System.out.println("JSON Output Generator");
}
}
// In Other Code, we write Output Generator like...
public class Class1 {
public void generateOutput() {
// Here Output will be in CSV-Format, because of hard-coded code.
// This method tightly coupled with CSVOutputGenerator class, if we want another Output, we must change this method.
// Any method, that calls Class1's generateOutput will return CSVOutput, because Class1 is tight couple with CSVOutputGenerator.
OutputGenerator outputGenerator = new CSVOutputGenerator();
output.generateOutput();
}
}
在上面的例子中,如果我们想要更改JSON中的输出,那么我们需要在整个代码中找到并更改,因为Class1与CSVOutputGenerator类紧密耦合。
松散耦合
public interface OutputGenerator {
public void generateOutput();
}
public class CSVOutputGenerator implements OutputGenerator {
public void generateOutput() {
System.out.println("CSV Output Generator");
}
}
public class JSONOutputGenerator implements OutputGenerator {
public void generateOutput() {
System.out.println("JSON Output Generator");
}
}
// In Other Code, we write Output Generator like...
public class Class1 {
public void generateOutput(OutputGenerator outputGenerator) {
// if you want to write JSON, pass object of JSONOutputGenerator (Dependency will be passed externally to this method)
// if you want to write CSV, pass object of CSVOutputGenerator (Dependency will be passed externally to this method)
// Due to loose couple with class, we don't need to change code of Class1, because Class1 is loose coupled with CSVOutputGenerator or JSONOutputGenerator class
// Any method, that calls Class1's generateOutput will desired output, because Class1 does not tight couple with CSVOutputGenerator or JSONOutputGenerator class
OutputGenerator outputGenerator = outputGenerator;
output.generateOutput();
}
}
我的理解是,与松散耦合的体系结构相比,紧密耦合的体系结构并没有为更改提供很多灵活性。
但是对于松散耦合的体系结构,消息格式或操作平台或修改业务逻辑不会影响另一端。如果系统因改造而关闭,当然另一端在一段时间内不能访问服务,但除此之外,未更改的一端可以恢复消息交换,就像改造之前一样。
松耦合是老式硬编码依赖关系和相关问题的答案,比如当任何事情发生变化时频繁重新编译和代码重用。它强调在组件中实现工作者逻辑,避免解决方案特定的连接代码。
松耦合= IoC 请看下面的解释。