美文网首页
桥接模式

桥接模式

作者: milovetingting | 来源:发表于2020-02-19 00:38 被阅读0次

个人博客

http://www.milovetingting.cn

桥接模式

模式介绍

桥接模式也称为桥梁模式,是结构型设计模式之一。

模式定义

将抽象部分与实现部分分离,使它们都可以独立地进行变化。

使用场景

  1. 一个系统需要在构件的抽象化角色和具体角色之间增加更多灵活性,避免在两个层次之间建立静态的继承关系,可以通过桥接模式使它们在抽象层建立一个关联关系。

  2. 不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统。

  3. 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

简单使用

定义抽象类

public abstract class CoffeeAdditives {
    public abstract String addSomething();
}

定义实现类

public class Sugar extends CoffeeAdditives {

    @Override
    public String addSomething() {
        return "加糖";
    }

}

public class Ordinary extends CoffeeAdditives{

    @Override
    public String addSomething() {
        return "原味";
    }

}

定义抽象类

public abstract class Coffee {

    protected CoffeeAdditives coffeeAdditives;

    public Coffee(CoffeeAdditives coffeeAdditives) {
        super();
        this.coffeeAdditives = coffeeAdditives;
    }

    public abstract void makeCoffee();

}

定义实现类

public class LargeCoffee extends Coffee {

    public LargeCoffee(CoffeeAdditives coffeeAdditives) {
        super(coffeeAdditives);
    }

    @Override
    public void makeCoffee() {
        System.out.println("大杯的" + coffeeAdditives.addSomething() + "咖啡");
    }

}

public class SmallCoffee extends Coffee {

    public SmallCoffee(CoffeeAdditives coffeeAdditives) {
        super(coffeeAdditives);
    }

    @Override
    public void makeCoffee() {
        System.out.println("小杯的" + coffeeAdditives.addSomething() + "咖啡");
    }

}

调用

public class Main {

    public static void main(String[] args) {
        Ordinary ordinary = new Ordinary();

        Sugar sugar = new Sugar();

        LargeCoffee largeCoffee = new LargeCoffee(ordinary);
        largeCoffee.makeCoffee();

        SmallCoffee smallCoffee = new SmallCoffee(ordinary);
        smallCoffee.makeCoffee();

        LargeCoffee largeCoffee2 = new LargeCoffee(sugar);
        largeCoffee2.makeCoffee();

        SmallCoffee smallCoffee2 = new SmallCoffee(sugar);
        smallCoffee2.makeCoffee();

    }

}

输出结果

大杯的原味咖啡
小杯的原味咖啡
大杯的加糖咖啡
小杯的加糖咖啡

相关文章

  • 设计模式-桥接模式

    设计模式-桥接模式 定义 桥接模式(Bridge Pattern)也称为桥梁模式、接口(Interface)模式或...

  • 结构型模式:桥接模式

    文章首发:结构型模式:桥接模式 七大结构型模式之二:桥接模式。 简介 姓名 :桥接模式 英文名 :Bridge P...

  • 设计模式之桥接模式

    设计模式之桥接模式 1. 模式定义 桥接模式又称柄体模式或接口模式,它是一种结构性模式。桥接模式将抽象部分与实现部...

  • 06-01-001 虚拟机的网络连接方式(转运整理)

    一、Bridged(桥接模式) 什么是桥接模式?桥接模式就是将主机网卡与虚拟机虚拟的网卡利用虚拟网桥进行通信。在桥...

  • 桥接模式与中介模式

    桥接模式-BRIDGE 对桥接模式感兴趣,是因为公司业务上需要桥接Html5和ReactNative两个平台。桥接...

  • 设计模式——桥接模式

    设计模式——桥接模式 最近公司组件分享设计模式,然而分配给我的是桥接模式。就在这里记录我对桥接模式的理解吧。 定义...

  • 桥接模式

    个人博客http://www.milovetingting.cn 桥接模式 模式介绍 桥接模式也称为桥梁模式,是结...

  • 桥接模式

    桥接模式 参考原文: https://zhuanlan.zhihu.com/p/62390221 定义 桥接模式 ...

  • 10-桥接模式

    桥接模式-Bridge Pattern【学习难度:★★★☆☆,使用频率:★★★☆☆】 处理多维度变化——桥接模式(...

  • Java设计模式——桥接模式

    Java设计模式之桥接模式 回顾 上一期分享了适配器模式,主要为了实现解耦 桥接模式 简介 桥接模式是对象的结构模...

网友评论

      本文标题:桥接模式

      本文链接:https://www.haomeiwen.com/subject/mnrofhtx.html