Java 中的耦合
耦合指一个对象使用另一个对象的情况。也可以称为协作。一个对象依赖于另一个对象来完成某些任务,可以分为以下两种类型 −
紧耦合 - 当一个对象创建要使用的对象时,它就是紧耦合的情况。由于主要对象创建对象本身,因此无法通过外部世界轻松更改此对象,从而将其标记为紧密耦合的对象。
松耦合 - 当一个对象从外部获取要使用的对象时,它就是松耦合的情况。由于主要对象仅是使用对象,因此可以从外部世界轻松更改对象,从而将其标记为松耦合对象。
示例 - 紧耦合
Tester.java
public class Tester {
public static void main(String args[]) {
A a = new A();
//a.display() will print A and B
//this implementation can not be changed dynamically
//being tight coupling
a.display();
}
}
class A {
B b;
public A() {
//b is tightly coupled to A
b = new B();
}
public void display() {
System.out.println("A");
b.display();
}
}
class B {
public B(){}
public void display() {
System.out.println("B");
}
}将产生以下结果 −
输出
A B
示例 - 松耦合
Tester.java
import java.io.IOException;
public class Tester {
public static void main(String args[]) throws IOException {
Show b = new B();
Show c = new C();
A a = new A(b);
//a.display() will print A and B
a.display();
A a1 = new A(c);
//a.display() will print A and C
a1.display();
}
}
interface Show {
public void display();
}
class A {
Show s;
public A(Show s) {
//s is loosely coupled to A
this.s = s;
}
public void display() {
System.out.println("A");
s.display();
}
}
class B implements Show {
public B(){}
public void display() {
System.out.println("B");
}
}
class C implements Show {
public C(){}
public void display() {
System.out.println("C");
}
}将产生以下结果 −
输出
A B A C
使用接口,我们可以通过注入依赖项来实现松耦合。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP