zoukankan      html  css  js  c++  java
  • 23种设计模式——桥接模式

    23种设计模式——桥接模式

    桥接模式

    • 将抽象部分与它的实现部分分离,使他们都可以独立地变化。是一种对象结构模式
    • 下面第一张图是我们经常看到的,要是用代码实现的话要分成很多很多的类,这显然不是我们想要的,违反了单一职责原则;桥接模式就是来解决这种问题,演变成了第二张图,通过连接点连接起来,但又不相互干扰。

    package com.mjh.bridge;
    
    public interface Brand {
        public void info();
    }
    
    
    //联想品牌
    class Lenovo implements Brand {
    
        @Override
        public void info() {
            System.out.print("联想");
        }
    }
    
    
    //苹果品牌
    class Apple implements Brand{
    
        @Override
        public void info() {
            System.out.print("苹果");
        }
    }
    
    package com.mjh.bridge;
    
    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("笔记本");
        }
    }
    
    package com.mjh.bridge;
    
    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();
        }
    }
    

    优点

    • 桥接模式偶尔类似于多继承,但是多继承方案违背了类的单一职责原则,复用性比较差,类的个数也比较多,桥接模式是比多继承方案更好的解决方法,极大地减少了子类个数,从而降低管理和维护成本
    • 桥接模式提高了子系统的可扩展性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。符合开闭原则,就像一座桥,可以把两个变化的维度连接起来

    缺点

    • 增加系统的立即与设计难度,由于聚合关联建立在抽象层,要求开发者针对抽象进行设计与编程
    • 要求正确失败系统中两个以上独立变化的维度,因此使用范围有一定局限性
  • 相关阅读:
    金融数据获取的api接口
    股票实时数据接口
    【C#】通过webbrowser控件自动注册QQ号讲解
    【C#】通过webbrowser控件获取验证码
    光圈,快门, 曝光,焦距, ISO,景深。
    装修记录
    cocos2dx在win10系统上的VS2017运行时报错:丢失MSVCR110.dll
    论打击的本质(2)-视觉理论及应用篇
    论打击感的本质(1)——力的理论及应用
    android屏幕适配详解
  • 原文地址:https://www.cnblogs.com/mjjh/p/13324429.html
Copyright © 2011-2022 走看看