• 设计模式 之 桥接模式


    简介

    桥接模式, 类似于棋盘组合. 使用java中的组合方式实现逻辑.

    code

    public class Test {
        public static void main(String[] args) {
            // 苹果笔记本
            // 联想台式机
            Computer computer = new Laptop(new Apple());
            computer.info();
            Computer computer1 = new Desktop(new Lenovo());
            computer1.info();
        }
    }
    
    
    public class Lenovo implements Brand {
        @Override
        public void info() {
            System.out.println("联想");
        }
    }
    
    
    public class Apple implements Brand {
        @Override
        public void info() {
            System.out.println("苹果电脑");
        }
    }
    
    public interface Brand {
        void info();
    }
    
    
    public abstract  class Computer {
        protected Brand brand;
        public Computer(Brand brand) {
            this.brand = brand;
        }
    
         public  void info() {
             brand.info();
         }
    }
    
    
    class Desktop extends Computer{
        public Desktop(Brand brand){
            super(brand);
        }
    
        @Override
        public void info() {
            super.info();
            System.out.println("台式机");
        }
    }
    
    class Laptop extends Computer{
        public Laptop(Brand brand) {
            super(brand);
        }
    
        @Override
        public void info() {
            super.info();
            System.out.println("笔记本");
        }
    }
    

    IMAGE

    UML

    可以看到 Brand 通过组合的方式融合进了 Computer.

    好处

    桥接模式偶尔类似于多继承方案, 但是多继承方案违背了类的单一职责原则, 复用性比较差,
    类的个数也非常多, 桥接模式是比多继承方案更好的解决方法. 极大的减少了子类的个数, 从而降低管理和维护的成本.

    桥接模式提高了系统的可扩展性, 在两个变化维度中任意扩展一个维度, 都不需要修改原有系统. 符合开闭原则, 就像一座桥, 可以把两个变化的维度连接起来!

    缺点

    桥接模式要求正确识别出系统中两个独立变化的维度, 因此其使用范围具有一定的局限性.

    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    阅读《构建之法(第三版)》提出的问题
    职位部门管理系统
    JSON
    hashcode()和equals()方法
    JSF和Facelets的生命周期
    认识applet
    认识ajax
    hello1.java分析
    vue中的防抖和节流
    vue项目搭建
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14820180.html
Copyright © 2020-2023  润新知