Java桥接模式

1 桥接模式

桥接模式是将抽象部分与它的实现部分分离,使他们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
在这里插入图片描述
上图一个类被三个类继承,使我们的程序扩展性,可维护性低,违反了单一职责原则。
在这里插入图片描述
具体代码实现如下:

  1. 创建品牌接口
package com.jialidun.gof.birdge;

//品牌
public interface Brand {

    void info();
}
  1. 创建计算机的抽象类
package com.jialidun.gof.birdge;

//抽象的电脑类型类
public abstract class Computer {

    //组合,品牌 桥
    protected Brand brand;

    public Computer(Brand brand){
        this.brand = brand;
    }

    public void info(){
        brand.info();//自带品牌

    }
}

  1. 苹果品牌
package com.jialidun.gof.birdge;

//苹果品牌
public class Apple implements Brand{
    @Override
    public void info() {
        System.out.print("苹果"+"\n");
    }
}

  1. 联想品牌
package com.jialidun.gof.birdge;

//联想品牌
public class Lenovo implements Brand{
    @Override
    public void info() {
        System.out.print("联想"+"\n");
    }
}

  1. 台式机
package com.jialidun.gof.birdge;

public class Desktop extends Computer{
    public Desktop(Brand brand) {
        super(brand);
        System.out.print("台式机");
    }
}

  1. 笔记本
package com.jialidun.gof.birdge;

public class laptop extends Computer{
    public laptop(Brand brand) {
        super(brand);
        System.out.print("笔记本");
    }
}

  1. 测试
package com.jialidun.gof.birdge;

public class Test {
    public static void main(String[] args) {
        //苹果笔记本
        Computer computer = new laptop(new Apple());
        computer.info();


        //联想台式机
        Desktop desktop = new Desktop(new Lenovo());
        desktop.info();


    }
}

在这里插入图片描述

好处分析:

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

劣势分析

  1. 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
  2. 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RYGAR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值