原文連接
譯者:smallclover
我的翻譯,水平有限,若有錯誤歡迎指出,謝謝!java
咱們使用橋來解耦(decouple )一個抽象以及該抽象的實現。使用橋以後抽象和實現能夠相互獨立的改變。這種類型的設計模式來源於結構型模式,它能夠經過使用橋結構來解耦抽象類及其實現類。設計模式
這種模式涉及一個接口,它扮演一個橋的角色,使得具體類的功能獨立與接口。這兩種類型的類能夠在不影響對方的狀況下改變自身結構。ide
咱們經過下面的例子來演示橋模式的使用。畫一個圓使用不一樣的顏色,相同的抽象類方法,不一樣的橋的具體實現者。this
咱們有一個DrawAPI接口,它扮演一個橋的實現化者的角色,而後會有具體的類RedCircle和GreenCircle實現接口DrawAPI。抽象類Shape將持有DrawAPI對象。BridgePatternDemo,咱們的demo類將使用Shape類畫兩個不一樣顏色的圓。spa
譯者注:bridge implementer 這裏翻譯爲橋的實現化者,它不一樣於具體的實現,如:繼承,實現。這裏的實現是指對橋這種概念的具體化,實現化。翻譯
建立一個橋的實現化者接口DrawAPI
DrawAPI.java設計
public interface DrawAPI { public void drawCircle(int radius, int x, int y); }
建立具體的類實現DrawApI接口
RedCircle.javacode
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 + "]"); } }
GreenCircle.javahtm
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 + "]"); } }
建立一個抽象類 Shape,該類持有一個DrawAPI接口的引用。
Shape.java對象
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); }
建立一個具體類實現抽象類Shape。
Circle.java
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); } }
使用Shape和DrawAPI類畫兩個不一樣顏色的圓。
BridgePatternDemo.java
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(); } }
校驗輸出。
Drawing Circle[ color: red, radius: 10, x: 100, 100] Drawing Circle[ color: green, radius: 10, x: 100, 100]