HTML 樣式例項
阿新 • • 發佈:2020-07-27
橋接模式(Bridge),使它的抽象部分與實現部分分離,使它們都可以獨立的變化。
什麼叫抽象與它的實現分離,這並不是說,讓抽象類與其派生類分離,因為這沒有任何意義。
實現指抽象類與它的派生類來實現自己的物件。
程式碼如下:
1 public abstract class Implementor { 2 public abstract void operation(); 3 }Implementor
1 /** 2 *派生類ConcreteImplementorA 3 */ 4 public class ConcreteImplementorA extends Implementor{ConcreteImplementorA5 6 @Override 7 public void operation() { 8 System.out.println("具體實現A的執行方法"); 9 10 } 11 12 }
1 public class ConcreteImplementorB extends Implementor{ 2 3 @Override 4 public void operation() { 5 System.out.println("具體實現B的執行方法");ConcreteImplementorB6 7 } 8 9 }
1 public class Abstraction { 2 protected Implementor implementor; 3 4 public void operation(){ 5 implementor.operation(); 6 } 7 public Implementor getImplementor() { 8 return implementor; 9 } 10 11 publicAbstractionvoid setImplementor(Implementor implementor) { 12 this.implementor = implementor; 13 } 14 15 16 }
1 public class RefineAbstraction extends Abstraction{ 2 @Override 3 public void operation() { 4 super.operation(); 5 } 6 }RefineAbstraction
1 public class BridgeTest { 2 public static void main(String[] args) { 3 Abstraction ab = new RefineAbstraction(); 4 ab.setImplementor(new ConcreteImplementorA()); 5 ab.operation(); 6 ab.setImplementor(new ConcreteImplementorB()); 7 ab.operation(); 8 } 9 }test
具體實現A的執行方法
具體實現B的執行方法
測試列印