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");
}
}这将生成以下结果 −
Output
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");
}
}这将生成以下结果 −
Output
A B A C
使用界面,我们可以通过注入依赖关系来实现松散耦合。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP