橋接(Bridge)是用于把抽象化與實現化解耦,使得二者可以獨立變化。這種類型的設計模式屬于結構型模式,它通過提供抽象化和實現化之間的橋接結構,來實現二者的解耦。
這種模式涉及到一個作為橋接的接口,使得實體類的功能獨立于接口實現類。這兩種類型的類可被結構化改變而互不影響。
優點: 1、抽象和實現的分離。 2、優秀的擴展能力。 3、實現細節對客戶透明。
缺點:橋接模式的引入會增加系統的理解與設計難度,由于聚合關聯關系建立在抽象層,要求開發者針對抽象進行設計與編程。
- 創建橋接實現接口。
/**
* 1. 創建橋接實現接口。
* @author mazaiting
*/
public interface DrawAPI {
/**
* 畫圓
* @param radius 半徑
* @param x 圓心橫坐標
* @param y 圓心縱坐標
*/
void drawCircle(int radius, int x,int y);
}
- 創建實現了 DrawAPI 接口的實體橋接實現類。
/**
* 2. 創建實現了 DrawAPI 接口的實體橋接實現類。
* @author mazaiting
*/
public class GreenCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}
}
/**
* 2. 創建實現了 DrawAPI 接口的實體橋接實現類。
* @author mazaiting
*/
public class RedCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}
}
- 使用 DrawAPI 接口創建抽象類 Shape。
/**
* 3. 使用 DrawAPI 接口創建抽象類 Shape。
* @author mazaiting
*/
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
/**
* 繪畫
*/
public abstract void draw();
}
- 創建實現了 Shape 接口的實體類。
/**
* 4. 創建實現了 Shape 接口的實體類。
* @author mazaiting
*/
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;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
- 主函數驗證
public class Client {
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, y: 100]
Drawing Circle[ color: green, radius: 10, x: 100, y: 100]