无涯教程-Java 桥接模式

65 阅读2分钟

桥接模式(Bride Pattern)将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。这种类型的设计模式属于结构模式,因为该模式通过在实现类和抽象类之间提供桥梁结构来使它们分离。

无涯教程通过以下示例演示桥接模式的使用,在该示例中,可以使用相同的抽象类方法但使用不同的桥实现程序类以不同的颜色绘制圆。

桥接模式实例

有一个 DrawAPI 接口,它充当桥实现者,而具体类 RedCircle , GreenCircle 实现了 DrawAPI 接口。 Shape 是一个抽象类,将使用 DrawAPI 的对象。 BridgePatternDemo ,演示类将使用 Shape 类绘制不同的彩色圆圈。

Bridge Pattern UML Diagram

第1步  -  创建DrawAPI接口。

DrawAPI.java

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

第2步  -  创建实现 DrawAPI 接口的具体实现类。

RedCircle.java

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 + "]");
   }
}

GreenCircle.java

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 + "]");
   }
}

第3步  -  使用 DrawAPI 接口创建抽象类 Shape 。

Shape.java

public abstract class Shape {
   protected DrawAPI drawAPI;

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

第4步  -  创建实现 Shape 接口的具体类。

Circle.java

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); } }

第5步  -  使用 Shape 和 DrawAPI 类绘制不同的彩色圆圈。

BridgePatternDemo.java

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</span><span class="pun">.</span><span class="pln">draw</span><span class="pun">();</span><span class="pln">
  greenCircle</span><span class="pun">.</span><span class="pln">draw</span><span class="pun">();</span><span class="pln">

} }

第6步  -  验证输出。

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

参考链接

www.learnfk.com/design-patt…