咱們以手機爲例,手機有品牌(諾基亞、摩托羅拉)和樣式(摺疊式、直立式),咱們須要生產不一樣的品牌和樣式,好比摺疊式諾基亞、直立式摩托羅拉... ...java
「抽象」 - 手機品牌,都有開機和關機的功能數據庫
public interface PhoneBrand { void open(); void close(); }
「具體」 - 手機品牌 Nokia 和 Moto編程
public class Nokia implements PhoneBrand { @Override public void open() { System.out.println("諾基亞開機..."); } @Override public void close() { System.out.println("諾基亞關機..."); } }
public class Moto implements PhoneBrand { @Override public void open() { System.out.println("摩托羅拉開機..."); } @Override public void close() { System.out.println("摩托羅拉關機..."); } }
「抽象」 - 手機類,以聚合的方式與品牌產生聯繫,充當着「橋」的角色設計模式
public abstract class AbsPhone{ private PhoneBrand brand; public AbsPhone(PhoneBrand brand) { this.brand = brand; } protected void open(){ brand.open(); } protected void close(){ brand.close(); } }
「具體」 - 摺疊式手機 和 直立式手機ide
public class FoldingPhone extends AbsPhone{ public FoldingPhone(PhoneBrand brand) { super(brand); } @Override protected void open() { System.out.print("摺疊式 - "); super.open(); } @Override protected void close() { System.out.print("摺疊式 - "); super.close(); } }
public class UpRightPhone extends AbsPhone{ public UpRightPhone(PhoneBrand brand) { super(brand); } @Override protected void open() { System.out.print("直立式 - "); super.open(); } @Override protected void close() { System.out.print("直立式 - "); super.close(); } }
測試測試
@Test public void test(){ AbsPhone p1 = new FoldingPhone(new Nokia()); p1.open(); p1.close(); System.out.println(); AbsPhone p2 = new UpRightPhone(new Moto()); p2.open(); p2.close(); }
結果this
摺疊式 - 諾基亞開機... 摺疊式 - 諾基亞關機... 直立式 - 摩托羅拉開機... 直立式 - 摩托羅拉關機...
若是咱們想建立其餘類型的手機,只須要改變建立方式便可。url
在 Java 中咱們一般使用 JDBC 鏈接數據庫,可是數據庫的種類有不少(MySQL、Oracle...),它們的鏈接方式、協議都不盡相同,很顯然不能爲每種數據庫都寫一個接口,這樣就違背了精簡設計原則,因而Java設計師就提供一套接口給廠商們本身實現,一套接口給用戶調用。設計
咱們在使用 JDBC 的時候須要寫這樣的代碼code
Class.forName("數據庫驅動名"); Connection conn = DriverManager.getConnection("數據庫url", "用戶名", "密碼");
其過程是這樣的:
Class.forName()
的時候,經過反射機制,將 .class
文件加載進Java虛擬機內存中,Driver
類初始化,執行如下代碼,向 DriverManager
中註冊一個驅動。DriverManager
是個 Driver
容器,管理不一樣的 Driver
static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } }
咱們獲取鏈接時,DriverManager
就會根據驅動返回一個相應的數據庫鏈接
@CallerSensitive public static Connection getConnection(String url, java.util.Properties info) throws SQLException { return (getConnection(url, info, Reflection.getCallerClass())); }
對於那些不但願使用繼承或由於多層次繼承致使系統類的個數急劇增長的系統,橋接模式尤其適用。