桥接模式

1991/6/26 结构型

# 定义

桥接模式(Bridge Pattern):是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

# 用途

在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。以画不同颜色的圆为例,实现共分五步:

  1. 创建桥接实现接口。

    public interface DrawAPI {
        void drawCircle(int radius, int x, int y);
    }
    
    1
    2
    3
  2. 创建实现了 DrawAPI 接口的实体桥接实现类。RedCircle、GreenCircle

    public class RedCircle implements DrawAPI {
    
        @Override
        public void drawCircle(int radius, int x, int y) {
            Log.e("---", "Drawing Circle[ color: red, radius: "
                    + radius + ", x: " + x + ", " + y + "]");
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
  3. 使用 DrawAPI 接口创建抽象类 Shape。

    public abstract class Shape {
    
        protected DrawAPI drawAPI;
    
        protected Shape(DrawAPI drawAPI) {
            this.drawAPI = drawAPI;
        }
    
        public abstract void draw();
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  4. 创建实现了 Shape 接口的实体类。

    public class Circle extends Shape {
    
        private int x, y, radius;
    
        protected Circle(int x, int y, int radius, DrawAPI drawAPI) {
            super(drawAPI);
            this.x = x;
            this.y = y;
            this.radius = radius;
        }
    
        @Override
        public void draw() {
            drawAPI.drawCircle(radius, x, y);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
  5. 使用 Shape 和 DrawAPI 类画出不同颜色的圆。

    // 画红圆
    Circle circle = new Circle(10, 10, 100, new RedCircle());s
    circle.draw();
    // 画绿圆
    Circle circle2 = new Circle(20, 20, 100, new GreenCircle());
    circle2.draw();
    
    1
    2
    3
    4
    5
    6