zoukankan      html  css  js  c++  java
  • 设计模式 之 桥接模式

    简介

    桥接模式, 类似于棋盘组合. 使用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
  • 相关阅读:
    GNU C的定义长度为0的数组
    Ubuntu如何启用双网卡
    DQN 文章第一篇
    awk用法
    Linux下C结构体初始化
    Linux kernel中的list怎么使用
    从美剧中学(1)
    Python @property 属性
    p40_数据交换方式
    3.TCP协议
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14820180.html
Copyright © 2011-2022 走看看