桥接模式通过将抽象与实现解耦,使二者可以根据需求独立变化。
桥接模式主要用于解决在需求多变的情况下使用继承造成类爆炸的问题。
(1)定义接口
public interface Driver{ void executeSQL(); }
(2)定义接口实现类
public class MysqlDriver implements Driver{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void executeSQL(){ logger.info("execute sql by mysql driver"); } } public class OracleDriver implements Driver{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void executeSQL(){ logger.info("execute sql by oracle driver"); } }
(3)定义桥接管理
public abstract class DriverManagerBridge{ private Driver driver; public void execute(){ this.driver.executeSQL(); } public Driver getDriver(){ return driver; } public void setDriver(Driver driver){ this.driver = driver; } }
(4)定义桥接
public class MyDriverBridge extends DriverManagerBridge{ public void execute(){ getDriver().executeSQL(); } }
(5)使用桥接模式
public static void main(String[] args){ DriverManagerBridge driverManagerBridge = new MyDriverBridge(); // 设置Mysql 驱动 driverManagerBridge.setDriver(new MysqlDriver()); driverManagerBridge.execute(); // 切换到Oracle驱动 driverManagerBridge.setDriver(new OracleDriver()); driverManagerBridge.execute(); }