定義
橋接(Bridge)是用于把抽象化與實作化解耦,使得二者可以獨立變化。這種類型的設計模式屬于結構型模式,它通過提供抽象化和實作化之間的橋接結構,來實作二者的解耦。
這種模式涉及到一個作為橋接的接口,使得實體類的功能獨立于接口實作類。這兩種類型的類可被結構化改變而互不影響。
我們通過下面的執行個體來示範橋接模式(Bridge Pattern)的用法。其中,可以使用相同的抽象類方法但是不同的橋接實作類,來畫出不同顔色的圓。
實作
我們有一個作為橋接實作的 DrawAPI 接口和實作了 DrawAPI 接口的實體類 RedCircle、GreenCircle。Shape 是一個抽象類,将使用 DrawAPI 的對象。BridgePatternDemo,我們的示範類使用 Shape 類來畫出不同顔色的圓。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZlBnaukTN2kjYzYmZ5kzMwEzYzUmZ0YWNzEjNzQ2YhJDOiZzYfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.jpeg)
橋接模式的 UML 圖
步驟 1
建立橋接實作接口。
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.draw();
greenCircle.draw();
}
}
步驟 6
驗證輸出。
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]