代码改变世界

桥接模式

2019-03-07 15:13  剑动情缥缈  阅读(192)  评论(0编辑  收藏  举报

1.基本概念

  • 将抽象化与实现化解耦
  • UML  

  

2.代码实现

package com.chengjie;

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

class RedCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: red, radius: " + radius +", x: " +x+", "+ y +"]");
    }
}
class GreenCircle implements DrawAPI {
    @Override
    public void drawCircle(int radius, int x, int y) {
        System.out.println("Drawing Circle[ color: green, radius: "
                + radius +", x: " +x+", "+ y +"]");
    }
}

abstract class Shape1 {
    public Shape1(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }

    protected DrawAPI drawAPI;
    public abstract void draw();
}

class Circle1 extends Shape1 {
    private int radius, x, y;

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

    @Override
    public void draw() {
        this.drawAPI.drawCircle(radius, x, y);
    }
}
public class TestBridge {
    public static void main(String[] args) {
        Circle1 redCircle = new Circle1(new RedCircle(),100, 10, 10);
        Circle1 greenCircle = new Circle1(new GreenCircle(),100, 10, 10);
        redCircle.draw();
        greenCircle.draw();
    }
}
View Code

3.优点

  • 抽象与实现分离
  • 当有新API时,容易扩展

4.缺点

  • 会增加系统的理解与设计难度

5.应用场景

  • 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展
  • JDBC

  

 

6.参考

   https://www.cnblogs.com/java-my-life/archive/2012/05/07/2480938.html

  http://www.runoob.com/design-pattern/bridge-pattern.html