橋接模式的目標(biāo)是使對象的抽象部分與實(shí)現(xiàn)部分分離,使之可以分別獨(dú)立變化,以盡量避免產(chǎn)生耦合。
下圖以繪制圓形為例:圓形的顏色通過接口類DrawAPI及其2個實(shí)現(xiàn)類RedCircle以及GreenCircle實(shí)現(xiàn);圓形的坐標(biāo)以及半徑通過抽象類及其擴(kuò)展類實(shí)現(xiàn),在實(shí)現(xiàn)draw()方法時,直接使用DrawAPI類中的相關(guān)對象的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("畫紅色圓,半徑"+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("畫綠色圓,半徑"+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文章
728瀏覽量
59872 -
API接口
+關(guān)注
關(guān)注
1文章
84瀏覽量
10519
發(fā)布評論請先 登錄
相關(guān)推薦
關(guān)于橋接模式遇到的問題
COM和CORBA的橋接與應(yīng)用
![COM和CORBA的<b class='flag-5'>橋</b><b class='flag-5'>接</b>與應(yīng)用](https://file.elecfans.com/web2/M00/48/92/pYYBAGKhtA-AElyqAAAf_opGaFw074.jpg)
DS31256 HDLC控制器的配置步驟—橋接模式
![DS31256 HDLC控制器的配置步驟—<b class='flag-5'>橋</b><b class='flag-5'>接</b><b class='flag-5'>模式</b>](https://file1.elecfans.com//web2/M00/A4/C9/wKgZomUMNbGAdFRyAABP33qtHKE817.gif)
網(wǎng)橋和橋接,網(wǎng)橋和橋接是什么意思
設(shè)計模式結(jié)構(gòu)性:橋接模式
![設(shè)計<b class='flag-5'>模式</b>結(jié)構(gòu)性:<b class='flag-5'>橋</b><b class='flag-5'>接</b><b class='flag-5'>模式</b>](https://file1.elecfans.com/web2/M00/89/54/wKgaomSBQZCAfx72AAJwl_WSJVA172.jpg)
遠(yuǎn)程網(wǎng)關(guān)橋接模式實(shí)現(xiàn)同一局域網(wǎng)組網(wǎng)管理(Superlink)
![遠(yuǎn)程網(wǎng)關(guān)<b class='flag-5'>橋</b><b class='flag-5'>接</b><b class='flag-5'>模式</b>實(shí)現(xiàn)同一局域網(wǎng)組網(wǎng)管理(Superlink)](https://file1.elecfans.com/web2/M00/82/4C/wKgaomRI0iWAUSYpAAB-9d72LWI796.png)
橋接模式應(yīng)用場景
![<b class='flag-5'>橋</b><b class='flag-5'>接</b><b class='flag-5'>模式</b>應(yīng)用場景](https://file1.elecfans.com/web2/M00/A9/27/wKgZomUjncmAPqbxAADwxlr76vQ148.jpg)
評論