橋接模式(bridge):java
把事物和其具體實現分開,使它們能夠各自獨立的變化。
橋接的用意是:數據庫
將抽象化與實現化解耦,使得兩者能夠獨立變化。
示例:oracle
橋接模式測試類(客戶端)Client.javaide
/** * 橋接模式測試類(客戶端) * * @author Kevin * @date 2016-3-15 */ public class Client { public static void main(String[] args) { AbstractDriverManager bridge = new DriverManager(); /* 使用MySQL數據庫驅動鏈接 */ Driver mySQLDriver = new MySQLDriverImpl(); bridge.setDriver(mySQLDriver); bridge.connect(); /* 使用Oracle數據庫驅動鏈接 */ Driver oracleDriver = new OracleDriverImpl(); bridge.setDriver(oracleDriver); bridge.connect(); } }
驅動橋類AbstractDriverManager.java測試
/** * 驅動橋 * * @author Kevin * @date 2016-3-15 */ public abstract class AbstractDriverManager { /* 驅動接口 */ private Driver driver; /** * 鏈接數據庫 * * @author Kevin */ public void connect() { driver.connect(); } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } }
驅動管理器類DriverManager.javathis
/** * 驅動管理器 * * @author Kevin * @date 2016-3-15 */ public class DriverManager extends AbstractDriverManager { @Override public void connect() { this.getDriver().connect(); } }
驅動接口類Driver.javacode
/** * 驅動接口 * * @author Kevin * @date 2016-3-15 */ public interface Driver { /** * 鏈接 * * @author Kevin */ void connect(); }
MySQL驅動接口實現類MySQLDriverImpl.java接口
/** * MySQL驅動接口實現類 * * @author Kevin * @date 2016-3-15 */ public class MySQLDriverImpl implements Driver { @Override public void connect() { System.out.println("use MySQLDriver connect MySQL database"); } }
Oracle驅動接口實現類OracleDriverImpl.javaget
/** * Oracle驅動接口實現類 * * @author Kevin * @date 2016-3-15 */ public class OracleDriverImpl implements Driver { @Override public void connect() { System.out.println("use OracleDriver connect Oracle database"); } }