橋接模式的目標(biāo)是使對(duì)象的抽象部分與實(shí)現(xiàn)部分分離,使之可以分別獨(dú)立變化,以盡量避免產(chǎn)生耦合。
下圖以繪制圓形為例:圓形的顏色通過(guò)接口類DrawAPI及其2個(gè)實(shí)現(xiàn)類RedCircle以及GreenCircle實(shí)現(xiàn);圓形的坐標(biāo)以及半徑通過(guò)抽象類及其擴(kuò)展類實(shí)現(xiàn),在實(shí)現(xiàn)draw()方法時(shí),直接使用DrawAPI類中的相關(guān)對(duì)象的drawCircle方法。
DrawAPI接口類:
package bridge;
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
RedCircle實(shí)現(xiàn)類:
package bridge;
public class RedCircle implements DrawAPI{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("畫(huà)紅色圓,半徑"+radius+",坐標(biāo):x="+x+",y="+y);
}
}
GreenCircle實(shí)現(xiàn)類:
package bridge;
public class GreenCircle implements DrawAPI{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("畫(huà)綠色圓,半徑"+radius+",坐標(biāo):x="+x+",y="+y);
}
}
Shape抽象類:
package bridge;
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI=drawAPI;
}
public abstract void draw();
}
Circle擴(kuò)展類:
package bridge;
public class Circle extends Shape{
int x, y, radius;
public Circle(DrawAPI drawAPI,int x,int y,int radius) {
super(drawAPI);
this.x=x;
this.y=y;
this.radius=radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
主函數(shù)調(diào)用方式:
package main;
import bridge.*;
public class BridgePattern {
public static void main(String[] args) {
Shape redCircle =new Circle(new RedCircle(),10,10,5);
Shape greenCircle = new Circle(new GreenCircle(),20,20,6);
redCircle.draw();
greenCircle.draw();
}
}
-
耦合器
+關(guān)注
關(guān)注
8文章
725瀏覽量
59686 -
API接口
+關(guān)注
關(guān)注
1文章
84瀏覽量
10437
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論