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

使用介面,我們可以透過注入依賴關係來實現鬆散耦合。

更新日期: 19-Jun-2020

超過 4k 次瀏覽

開啟你的 職業生涯

透過完成這門課程獲得認證

學習入門
廣告