• 设计模式之 桥接模式


    桥接模式通过将抽象与实现解耦,使二者可以根据需求独立变化。

    桥接模式主要用于解决在需求多变的情况下使用继承造成类爆炸的问题。

    image

    (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();
    }

  • 相关阅读:
    elasticSearch 查询 bool
    elasticSearch 查询 term
    elasticSearch 查询 match
    python re
    vue day1
    mysql 报错记录
    node.js vue.js 安装
    mysql 插入数据 ,存在跳过
    打印乘法口诀表
    初步使用分支、循环判断数字大小
  • 原文地址:https://www.cnblogs.com/betterwgo/p/15232709.html
Copyright © 2020-2023  润新知