橋樑模式的用意是"將抽象化(Abstraction)與實現化(Implementation)脫耦, 將"類的功能層次結構" 與 "類的實現層次結構"分離爲兩個獨立的類層次結構.java
public interface DisplayImpl { void rawOpen(); void rawPrint(); void rawClose(); }
public class StringDisplayImpl implements DisplayImpl { private String string; private int width; public StringDisplayImpl(String string) { this.string = string; this.width = string.getBytes().length; } public void rawOpen() { printLine(); } public void rawPrint() { System.out.println("|" + string + "|"); } public void rawClose() { printLine(); } private void printLine() { System.out.print("+"); for (int i = 0; i < width; i++) { System.out.print("-"); } System.out.println("+"); } }
在功能實現的最高層上關聯了DisplayImpl接口, 在此處進行了橋接.測試
public class Display { private DisplayImpl impl; public Display(DisplayImpl impl) { this.impl = impl; } public void open() { impl.rawOpen(); } public void print() { impl.rawPrint(); } public void close() { impl.rawClose(); } public final void display() { open(); print(); close(); } }
在Display類的基礎上, 進行功能上的擴展. 擴展一個multiDisplay()功能.this
public class CountDisplay extends Display { public CountDisplay(DisplayImpl impl) { super(impl); } public void multiDisplay(int times) { open(); for (int i = 0; i < times; i++) { print(); } close(); } }
用於測試運行spa
public class Main { public static void main(String[] args) { Display d1 = new Display(new StringDisplayImpl("Hello, China.")); Display d2 = new CountDisplay(new StringDisplayImpl("Hello, World.")); CountDisplay d3 = new CountDisplay(new StringDisplayImpl("Hello, Universe.")); d1.display(); d2.display(); d3.display(); d3.multiDisplay(5); } }