《桥接模式》

1.桥接模式介绍

  • 优点:
    • 抽象部分和实现部分的解耦(分离),他们两个互相独立,不会影响到对方。
    • 优秀的扩展能力。
    • 实现细节对客户透明。
  • 缺点: 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
  • 本质: 就是2个变量(对象)的排列组合
  • 使用场景: 对于两个独立变化的维度,使用桥接模式再适合不过了。

2.桥接模式的简单使用

在这里插入图片描述

//手机品牌和款式组合的桥梁,内部维护款式接口
public abstract class PhoneBridge {
    protected Style style;
    protected String brand;
    public abstract void make();
}
//苹果手机
public class ApplePhone extends PhoneBridge{
    public ApplePhone(Style style) {
        this.style = style;
        this.brand = "苹果";
    }
    @Override
    public void make() {
        System.out.println("生产=>"+this.brand+this.style.type()+"手机");
    }
}
//华为手机
public class HuaWeiPhone extends PhoneBridge{
    public HuaWeiPhone(Style style) {
        this.style = style;
        this.brand = "华为";
    }
    @Override
    public void make() {
        System.out.println("生产=>"+this.brand+this.style.type()+"手机");
    }
}

//手机款式的统一接口
public interface Style{
    String type();
}

public class FoldingStyle implements Style{
    @Override
    public String type() {
        return "折叠式";
    }
}

public class UprightStyle implements Style{
    @Override
    public String type() {
        return "直立式";
    }
}

public class RotatingStyle implements Style{
    @Override
    public String type() {
        return "旋转式";
    }
}

public class Test{
    public static void main(String[] args) {
        ApplePhone appleFolding = new ApplePhone(new FoldingStyle());
        appleFolding.make();

        ApplePhone appleRotating = new ApplePhone(new RotatingStyle());
        appleRotating.make();

        HuaWeiPhone huaWeiUpright = new HuaWeiPhone(new UprightStyle());
        huaWeiUpright.make();
    }
}
		生产=>苹果折叠式手机
		生产=>苹果旋转式手机
		生产=>华为直立式手机
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值