橋接模式

橋接模式

將抽象部分與實現部分分離,使它們均可以獨立的變化。html

使用場景: 一、若是一個系統須要在構件的抽象化角色和具體化角色之間增長更多的靈活性,避免在兩個層次之間創建靜態的繼承聯繫,經過橋接模式可使它們在抽象層創建一個關聯關係。 二、對於那些不但願使用繼承或由於多層次繼承致使系統類的個數急劇增長的系統,橋接模式尤其適用。 三、一個類存在兩個獨立變化的維度,且這兩個維度都須要進行擴展。ide


一、建立橋接接口

1 public interface DrawAPI {
2     void draw(int radius,int x,int y);
3 }
DrawAPI

二、橋接接口的實現類

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 }
GreenCircle
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 }
RedCircle

三、 建立將使用橋接接口DrawAPI 的對象抽象類Shape

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 }
Shape

四、抽象類Shape的具體實現類

 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 }
Circle

五、測試類

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 }
BridagePatternDemo

六、測試結果

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測試

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息