介紹
將類的功能層次結構和實現層次結構相分離,使二者能夠獨立地變化,並在兩者之間搭建橋樑,實現橋接,將抽象和實現放在兩個不同的類層次中,使它們可以獨立地變化。
優點
1、抽象和實現的分離。 2、優秀的擴展能力。 3、實現細節對客戶透明。
缺點
橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與編程。
使用場景
1、如果一個系統需要在構件的抽象化角色和具體化角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的繼承聯繫,通過橋接模式可以使它們在抽象層建立一個關聯關係。
2、對於那些不希望使用繼承或因爲多層次繼承導致系統類的個數急劇增加的系統,橋接模式尤爲適用。
3、一個類存在兩個獨立變化的維度,且這兩個維度都需要進行擴展。
使用建議
對於兩個獨立變化的維度,使用橋接模式再適合不過了。
具體實現
類圖:
代碼:
實現者角色:
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
public interface DrawAPI {
public abstract void drawCircle(int radius, int x, int y);
}
具體實現者角色:
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
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 +"]");
}
}
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
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 +"]");
}
}
抽象者角色:
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
具體抽象者角色:
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
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);
}
}
package com.knowledge.system.software_design_pattern.bridge_pattern.myself_instance;
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();
}
}