桥接模式

桥接模式

将抽象部分与实现部分分离,使它们都可以独立的变化。

使用场景: 1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。 2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。 3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。


1、创建桥接接口

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

2、桥接接口的实现类

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

3、 创建将使用桥接接口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

4、抽象类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

5、测试类

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

6、测试结果

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

posted @ 2019-11-26 09:19  honghj  阅读(318)  评论(0编辑  收藏  举报