美文网首页
2019-03-03桥接模式

2019-03-03桥接模式

作者: Aluha_f289 | 来源:发表于2019-03-03 10:57 被阅读0次

桥接模式

桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。

意图:将抽象部分与实现部分分离,使它们都可以独立的变化。

主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。

使用场景:一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

注意点:
    1、定义一个桥接口,使其与一方绑定,这一方的扩展全部使用实现桥接口的方式。
    2、定义一个抽象类,来表示另一方,在这个抽象类内部要引入桥接口,而这一方的扩展全部使用继承该抽象类的方式。

实现

步骤一、创建桥接实现接口。

public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}

步骤二、创建实现了 DrawAPI 接口的实体桥接实现类。

public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}
public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}

步骤三、使用 DrawAPI 接口创建抽象类 Shape。

public abstract class Shape {
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();  
}

步骤四、创建实现了 Shape 接口的实体类。

public class Circle extends Shape {
   private int x, y, radius;
 
   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }
 
   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}

步骤五、使用 Shape 和 DrawAPI 类画出不同颜色的圆。

public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
 
      redCircle.draw();
      greenCircle.draw();
   }
}

步骤六、执行程序,输出结果:

Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]

参考博客地址http://www.runoob.com/design-pattern/bridge-pattern.html

相关文章

  • 2019-03-03桥接模式

    桥接模式 桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。 意图:将抽象部分与实现部分分离,...

  • 设计模式-桥接模式

    设计模式-桥接模式 定义 桥接模式(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【学习难度:★★★☆☆,使用频率:★★★☆☆】 处理多维度变化——桥接模式(...

网友评论

      本文标题:2019-03-03桥接模式

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