將抽象部分與實現部分分離,使它們均可以獨立的變化。html
使用場景: 一、若是一個系統須要在構件的抽象化角色和具體化角色之間增長更多的靈活性,避免在兩個層次之間創建靜態的繼承聯繫,經過橋接模式可使它們在抽象層創建一個關聯關係。 二、對於那些不但願使用繼承或由於多層次繼承致使系統類的個數急劇增長的系統,橋接模式尤其適用。 三、一個類存在兩個獨立變化的維度,且這兩個維度都須要進行擴展。ide
1 public interface DrawAPI { 2 void draw(int radius,int x,int y); 3 }
1 public class GreenCircle implements DrawAPI { 2 @Override 3 public void draw(int radius, int x, int y) { 4 System.out.println("Drawing Circle[ color: green, radius: " 5 + radius +", x: " +x+", "+ y +"]"); 6 } 7 }
1 public class RedCircle implements DrawAPI { 2 @Override 3 public void draw(int radius, int x, int y) { 4 System.out.println("Drawing Circle[ color: green, radius: " 5 + radius +", x: " +x+", "+ y +"]"); 6 } 7 }
1 public abstract class Shape { 2 protected DrawAPI drawAPI; 3 protected Shape(DrawAPI drawAPI){ 4 this.drawAPI = drawAPI; 5 } 6 public abstract void draw(); 7 }
1 public class Circle extends Shape { 2 private int x; 3 private int y; 4 private int radius; 5 public Circle(int x, int y,int radius,DrawAPI drawAPI){ 6 super(drawAPI); 7 this.x = x; 8 this.y = y; 9 this.radius = radius; 10 } 11 12 @Override 13 public void draw() { 14 drawAPI.draw(x,y,radius); 15 } 16 }
1 public class BridagePatternDemo { 2 3 public static void main(String[] args) { 4 Shape redCicle = new Circle(5,3,4,new RedCircle()); 5 Shape greenCircle = new Circle(2,1,4,new GreenCircle()); 6 redCicle.draw(); 7 greenCircle.draw(); 8 } 9 }
Drawing Circle[ color: green, radius: 5, x: 3, 4]
Drawing Circle[ color: green, radius: 2, x: 1, 4]
轉載自:https://www.runoob.com/design-pattern/bridge-pattern.html測試