桥接模式(bridge):
把事物和其具体实现分开,使它们可以各自独立的变化。
桥接的用意是:
将抽象化与实现化解耦,使得二者可以独立变化。
示例:
桥接模式测试类(客户端)Client.java
/** * 桥接模式测试类(客户端) * * @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.java
/** * 驱动管理器 * * @author Kevin * @date 2016-3-15 */public class DriverManager extends AbstractDriverManager { @Override public void connect() { this.getDriver().connect(); }}
驱动接口类Driver.java
/** * 驱动接口 * * @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.java
/** * Oracle驱动接口实现类 * * @author Kevin * @date 2016-3-15 */public class OracleDriverImpl implements Driver { @Override public void connect() { System.out.println("use OracleDriver connect Oracle database"); }}