橋接(Bridge)是用于把抽象化與實(shí)現(xiàn)化解耦舔亭,使得二者可以獨(dú)立變化书蚪。這種類(lèi)型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它通過(guò)提供抽象化和實(shí)現(xiàn)化之間的橋接結(jié)構(gòu)浦马,來(lái)實(shí)現(xiàn)二者的解耦时呀。
這種模式涉及到一個(gè)作為橋接的接口,使得實(shí)體類(lèi)的功能獨(dú)立于接口實(shí)現(xiàn)類(lèi)晶默。這兩種類(lèi)型的類(lèi)可被結(jié)構(gòu)化改變而互不影響谨娜。
優(yōu)點(diǎn): 1、抽象和實(shí)現(xiàn)的分離磺陡。 2趴梢、優(yōu)秀的擴(kuò)展能力。 3币他、實(shí)現(xiàn)細(xì)節(jié)對(duì)客戶透明垢油。
缺點(diǎn):橋接模式的引入會(huì)增加系統(tǒng)的理解與設(shè)計(jì)難度,由于聚合關(guān)聯(lián)關(guān)系建立在抽象層圆丹,要求開(kāi)發(fā)者針對(duì)抽象進(jìn)行設(shè)計(jì)與編程滩愁。
- 創(chuàng)建橋接實(shí)現(xiàn)接口。
/**
* 1. 創(chuàng)建橋接實(shí)現(xiàn)接口辫封。
* @author mazaiting
*/
public interface DrawAPI {
/**
* 畫(huà)圓
* @param radius 半徑
* @param x 圓心橫坐標(biāo)
* @param y 圓心縱坐標(biāo)
*/
void drawCircle(int radius, int x,int y);
}
- 創(chuàng)建實(shí)現(xiàn)了 DrawAPI 接口的實(shí)體橋接實(shí)現(xiàn)類(lèi)硝枉。
/**
* 2. 創(chuàng)建實(shí)現(xiàn)了 DrawAPI 接口的實(shí)體橋接實(shí)現(xiàn)類(lèi)。
* @author mazaiting
*/
public class GreenCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}
}
/**
* 2. 創(chuàng)建實(shí)現(xiàn)了 DrawAPI 接口的實(shí)體橋接實(shí)現(xiàn)類(lèi)倦微。
* @author mazaiting
*/
public class RedCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}
}
- 使用 DrawAPI 接口創(chuàng)建抽象類(lèi) Shape妻味。
/**
* 3. 使用 DrawAPI 接口創(chuàng)建抽象類(lèi) Shape。
* @author mazaiting
*/
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
/**
* 繪畫(huà)
*/
public abstract void draw();
}
- 創(chuàng)建實(shí)現(xiàn)了 Shape 接口的實(shí)體類(lèi)欣福。
/**
* 4. 創(chuàng)建實(shí)現(xiàn)了 Shape 接口的實(shí)體類(lèi)责球。
* @author mazaiting
*/
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;
}
@Override
public void draw() {
drawAPI.drawCircle(radius, x, y);
}
}
- 主函數(shù)驗(yàn)證
public class Client {
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();
}
}
- 打印結(jié)果
Drawing Circle[ color: red, radius: 10, x: 100, y: 100]
Drawing Circle[ color: green, radius: 10, x: 100, y: 100]