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

使用介面,我們可以透過注入依賴項來實現松耦合。

更新於: 19-6 月-2020

4K+ 檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告