1 public class BridgeTest { 2 public static void main(String[] args) { 3 Abstraction imp = new RefinedAbstraction(new ConcreteImplementorA()); 4 imp.operation(); 5 } 6 7 } 8 //抽象化角色 9 abstract class Abstraction{ 10 //實現化角色 11 protected Implementor imp; 12 13 //經過向實現化角色委派完成 14 public void operation(){ 15 imp.operationImp(); 16 } 17 } 18 //修正抽象化角色 19 class RefinedAbstraction extends Abstraction{ 20 public RefinedAbstraction(Implementor imp){ 21 this.imp = imp; 22 } 23 24 //修正化角色能夠置換掉實現化角色的方法 25 public void operation(){ 26 System.out.println("Do anotherThing...."); 27 } 28 } 29 //實現化角色 30 abstract class Implementor{ 31 public abstract void operationImp(); 32 } 33 34 //具體實現化角色 35 class ConcreteImplementorA extends Implementor{ 36 37 @Override 38 public void operationImp() { 39 System.out.println("Do something...."); 40 } 41 42 }
橋樑模式是「對變化的封裝」原則以及組合、聚合複用原則的極好的例子。在飛機制造系統中,飛機的種類和製造商表明兩個不一樣的變化因素,而這兩個變化因素須要獨立地變化。按照對變化的封裝原則,它們應當被封裝到繼承的等級結構中,而這兩個等級結構之間應當選擇使用聚合關係,避免出現靜態的強耦合,這就致使了橋樑模式的設計方案。java