重走Java設計模式——橋接模式(Bridge Pattern)
阿新 • • 發佈:2018-11-09
橋接模式
定義
將抽象部分與實現部分分離,使它們都可以獨立的變化。
結構詳解
橋接模式主要包含如下幾個角色:
1.Abstraction:抽象類;
2.RefinedAbstraction:擴充抽象類;
3.Implementor:實現類介面;
4.ConcreteImplementor:具體實現類 。
結構圖
程式碼示例
建立一個橋接實現的DrawAPI
介面和實現了DrawAPI
介面的實體類 RedCircle
、GreenCircle
。Shape
是一個抽象類,將使用 DrawAPI
的物件。BridgePatternDemo
Shape
類來畫出不同顏色的圓。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]
模式的優缺點
優點
- 抽象和實現的分離,提高了比繼承更好的解決方案;
- 優秀的擴充套件能力,在兩個變化維度中任意擴充套件一個維度,都不需要修改原有系統;
- 實現細節對客戶透明,可以對使用者隱藏實現細節。
缺點
橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與程式設計。
使用場景
- 如果一個系統需要在構件的抽象化角色和具體化角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的繼承聯絡,通過橋接模式可以使它們在抽象層建立一個關聯關係;
- 對於那些不希望使用繼承或因為多層次繼承導致系統類的個數急劇增加的系統,橋接模式尤為適用;
- 一個類存在兩個獨立變化的維度,且這兩個維度都需要進行擴充套件。