(6)桥接模式-结构型

属于结构型模式,用于抽象与实现解耦。
例如:
JDBC获取数据库连接,是实现桥接模式的典型。参考:JDBC桥接

代码示例

public interface DrawAPI {
    void drawCircle(int radius, int x, int y);
}

public class DrawBlueCircle implements DrawAPI{

    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("draw blue circle,radius:"
                + radius + ",x:" + x + ",y:" + y);
    }
}

public class DrawRedCircle implements DrawAPI {

    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("draw red circle,radius:" + radius + ",x:"
                + ",y:" + y);

    }
}
// 关键
public abstract class Shape {
    // 依赖接口,不依赖具体实现
    public DrawAPI drawAPI;

    public Shape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }

    public abstract void draw();

}

public class Circle extends Shape{
    // 类属性,数据类型采用包装类  阿里巴巴开发手册,并且每行一个属性
    private Integer radius;
    private Integer x;
    private Integer y;

    public Circle(DrawAPI drawAPI, Integer radius, Integer x, Integer y) {
        super(drawAPI);
        this.radius = radius;
        this.x = x;
        this.y = y;
    }

    @Override
    public void draw() {
        drawAPI.drawCircle(radius,x,y);
    }
}

//测试客户端
public class BridgePatternDemo {
    public static void main(String[] args) {
        final Circle redCircle = new Circle(new DrawRedCircle(), 1, 5, 5);
        final Circle blueCircle = new Circle(new DrawBlueCircle(), 10, 3, 5);

        redCircle.draw();
        blueCircle.draw();

    }
}
/**
* 运行结果:
* draw red circle,radius:1,x:,y:5
* draw blue circle,radius:10,x:3,y:5
*/

个人疑惑:桥接模式、策略模式从表面上很像,这俩有啥区别呢?
1、很像的原因:Bridge模式和Strategy模式相似就是因为他们都将任务委托给了另外一个接口的具体实现。
2、区别:
(1)Bridge的目的是让底层实现和上层接口可以分别演化,从而提高移植性,而Strategy的目的是将复杂的算法封装起来,从而便于替换不同的算法。
因此可以想象一般情况下Bridge的实现几乎不会在运行时更改而Strategy的算法则很有可能需要在运行时更换,这就导致在细节方面需要考虑的因素可能会很不相同。
(2)bridge模式是往往是为了利用已有的方法或类。
参考桥接与策略的区别讨论

原文地址:https://www.cnblogs.com/xingrui/p/13247068.html