橋接模式分析
用於把抽象化與實現化解耦,使得二者可以獨立變化。通過提供抽象化和實現化之間的橋接結構,來實現二者的解耦。
類圖示例
代碼示例
//橋接模式
public class BridgeModule {
interface DrawAPI{
void drawCircle(int radius, int x, int y);
}
static 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 +"]");
}
}
static 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 +"]");
}
}
static abstract class Shape{
DrawAPI drawAPI;
Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
static class Circle extends Shape{
private int x, y, radius;
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 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();
}
}
優點:
- 抽象和實現的分離。
- 優秀的擴展能力。
- 實現細節對客戶透明。
缺點:
- 橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與編程。