Java二十三設計模式之-----橋接模式

來源:互聯網
上載者:User

標籤:實作類別   --   log   ide   統一   接下來   post   manager   介面   

一、橋接模式 (Bridge)

橋接模式就是把事物和其具體實現分開,使他們可以各自獨立的變化。橋接的用意是:將抽象化與實現化解耦,使得二者可以獨立變化,像我們常用的JDBC橋DriverManager一樣,JDBC進行串連資料庫的時候,在各個資料庫之間進行切換,基本不需要動太多的代碼,甚至絲毫不用動,原因就是JDBC提供統一介面,每個資料庫提供各自的實現,用一個叫做資料庫驅動的程式來橋接就行了。我們來看看關係圖:

實現代碼:

先定義介面:

 
  1. public interface Sourceable {  
  2.     public void method();  
  3. }  

分別定義兩個實作類別:

 
  1. public class SourceSub1 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the first sub!");  
  6.     }  
  7. }  
 
  1. public class SourceSub2 implements Sourceable {  
  2.   
  3.     @Override  
  4.     public void method() {  
  5.         System.out.println("this is the second sub!");  
  6.     }  
  7. }  

定義一個橋,持有Sourceable的一個執行個體:

 
  1. public abstract class Bridge {  
  2.     private Sourceable source;  
  3.   
  4.     public void method(){  
  5.         source.method();  
  6.     }  
  7.       
  8.     public Sourceable getSource() {  
  9.         return source;  
  10.     }  
  11.   
  12.     public void setSource(Sourceable source) {  
  13.         this.source = source;  
  14.     }  
  15. }  
 
  1. public class MyBridge extends Bridge {  
  2.     public void method(){  
  3.         getSource().method();  
  4.     }  
  5. }  

測試類別:

 
  1. public class BridgeTest {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         Bridge bridge = new MyBridge();  
  6.           
  7.         /*調用第一個對象*/  
  8.         Sourceable source1 = new SourceSub1();  
  9.         bridge.setSource(source1);  
  10.         bridge.method();  
  11.           
  12.         /*調用第二個對象*/  
  13.         Sourceable source2 = new SourceSub2();  
  14.         bridge.setSource(source2);  
  15.         bridge.method();  
  16.     }  
  17. }  

output:

this is the first sub!
this is the second sub!

這樣,就通過對Bridge類的調用,實現了對介面Sourceable的實作類別SourceSub1和SourceSub2的調用。接下來我再畫個圖,大家就應該明白了,因為這個圖是我們JDBC串連的原理,有資料庫學習基礎的,一結合就都懂了。

來源 https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html

Java二十三設計模式之-----橋接模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.