Github:BridgePattern
桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。
这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。

  1. 定义形状枚举类。此枚举类可以不用,仅仅是打印时区分

    1. public enum ShapeEnums{
    2. CIRCLE, RECTANGLE
    3. ;
    4. }
  2. 定义画图接口及实现类 ```java /**

    • 定义画图接口 */ public interface DrawApi{ void draw(ShapeEnums shapeEnums, int x, int y, int raduis); }

/**

  • 实现画图接口,画红色 */ public class RedDraw implements DrawApi{ @Override public void draw(ShapeEnums shapeEnums, int x, int y, int raduis) {
    1. System.out.println(String.format("draw red %s. [x: %s, y: %s, raduis: %s]", shapeEnums, x, y, raduis));
    } }

/**

  • 实现画图接口,画蓝色 */ public class BlueDraw implements DrawApi{ @Override public void draw(ShapeEnums shapeEnums, int x, int y, int raduis) {
    1. System.out.println(String.format("draw blue %s. [x: %s, y: %s, raduis: %s]", shapeEnums, x, y, raduis));
    } } ```
  1. 定义形状抽象类及实现类 ```java /**

    • 形状抽象类 */ public abstract class Shape{ protected DrawApi drawApi;

      protected Shape(DrawApi drawApi) { this.drawApi = drawApi; }

      /**

      • 虽然这里也可以有具体实现,但为了解耦,各自形状有各自的draw逻辑。所以这里只定义 */ protected abstract void draw(); }

/**

  • 实现形状抽象类,定义具体形状 */ public class Circle extends Shape{ int x, y, raduis; private ShapeEnums shapeEnums = ShapeEnums.CIRCLE;

    public Circle(int x, int y, int raduis, DrawApi drawApi) {

    1. super(drawApi);
    2. this.x = x;
    3. this.y = y;
    4. this.raduis = raduis;

    }

    @Override protected void draw() {

    1. drawApi.draw(shapeEnums, x, y, raduis);

    } }

/**

  • 矩形 */ public class Rectangle extends Shape{ int x, y, raduis; private ShapeEnums shapeEnums = ShapeEnums.RECTANGLE;

    public Rectangle(int x, int y, int raduis, DrawApi drawApi) {

    1. super(drawApi);
    2. this.x = x;
    3. this.y = y;
    4. this.raduis = raduis;

    }

    /**

    • 虽然这里也可以有具体实现,但为了解耦,各自形状有各自的draw逻辑。所以这里只定义 */ @Override protected void draw() { drawApi.draw(shapeEnums, x,y, raduis); } } ```
  1. 测试 ```java public static void main(String[] args) { BridgePattern pattern = new BridgePattern(); pattern.bridge(); }

private void bridge() { // 画蓝色圆形 Circle circle = new Circle(10, 20, 100, new BlueDraw()); circle.draw();

  1. // 画红色圆形
  2. circle = new Circle(10, 20, 200, new RedDraw());
  3. circle.draw();
  4. // 画红色矩形
  5. Rectangle rectangle = new Rectangle(20,30,400, new RedDraw());
  6. rectangle.draw();

}

  1. 输出结果:
  2. ```java
  3. draw blue CIRCLE. [x: 10, y: 20, raduis: 100]
  4. draw red CIRCLE. [x: 10, y: 20, raduis: 200]
  5. draw red RECTANGLE. [x: 20, y: 30, raduis: 400]

参考:

菜鸟教程 - 桥接模式