橋接模式就是把事物和其具體實現分開,使他們能夠各自獨立的變化。橋接的用意是:將抽象化與實現化解耦,使得兩者能夠獨立變化,像咱們經常使用的JDBC橋DriverManager同樣,JDBC進行鏈接數據庫的時候,在各個數據庫之間進行切換,基本不須要動太多的代碼,甚至絲絕不用動,緣由就是JDBC提供統一接口,每一個數據庫提供各自的實現,用一個叫作數據庫驅動的程序來橋接就好了。咱們來看看關係圖:java
實現代碼:數據庫
先定義接口:ide
public interface Sourceable { public void method(); }
分別定義兩個實現類:學習
public class SourceSub1 implements Sourceable { @Override public void method() { System.out.println("this is the first sub!"); } }
public class SourceSub2 implements Sourceable { @Override public void method() { System.out.println("this is the second sub!"); } }
定義一個橋,持有Sourceable的一個實例:測試
public abstract class Bridge { private Sourceable source; public void method(){ source.method(); } public Sourceable getSource() { return source; } public void setSource(Sourceable source) { this.source = source; } }
public class MyBridge extends Bridge { public void method(){ getSource().method(); } }
測試類:this
public class BridgeTest { public static void main(String[] args) { Bridge bridge = new MyBridge(); /*調用第一個對象*/ Sourceable source1 = new SourceSub1(); bridge.setSource(source1); bridge.method(); /*調用第二個對象*/ Sourceable source2 = new SourceSub2(); bridge.setSource(source2); bridge.method(); } }
output:code
this is the first sub!
this is the second sub!對象
這樣,就經過對Bridge類的調用,實現了對接口Sourceable的實現類SourceSub1和SourceSub2的調用。接下來我再畫個圖,你們就應該明白了,由於這個圖是咱們JDBC鏈接的原理,有數據庫學習基礎的,一結合就都懂了。接口