设计模式——桥接模式

179 阅读2分钟

一、概述

桥的作用就是连接两个地方,桥接模式的作用和这十分类似,就是连接抽象部分和实现部分,起到解耦的作用。桥接模式它是一种结构性模式。桥接使得具体类与接口实现者类无关,这两种类型的类可以改变但不会影响对方。

下面以用画出不同颜色和形状为例,具体说明以下。

二、使用

首先定义一个绘制圆形的接口(可以使用抽象类),里面只有一个绘制方法。

/**
 * 绘制接口
 */
public interface DrawInterface {
    void drawCircle(int radius, int x, int y);
}

然后是创建实现了绘制圆形接口的实现类。

public class RedCircle implements DrawInterface {

    @Override
    public void drawCircle(int radius, int x, int y) {
        Log.e(TAG, "绘制红色圆形,半径:" + radius + ",X坐标:" + x + ",y坐标:" + y);
    }
}
public class GreenCircle implements DrawInterface {

    @Override
    public void drawCircle(int radius, int x, int y) {
        Log.e(TAG, "绘制绿色圆形,半径:" + radius + ",X坐标:" + x + ",y坐标:" + y);
    }
}

接下来通过绘制接口创建形状抽象类。

public abstract class Shape {

    protected DrawInterface drawInterface;

    public Shape(DrawInterface drawInterface){
        this.drawInterface = drawInterface;
    }

    public abstract void draw();
}

再者创建Shape的具体实现类。

public class Circle extends Shape {

    private int x, y, radius;

    public Circle(DrawInterface drawInterface, int x, int y, int radius) {
        super(drawInterface);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

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

最后进行测试,代码打印输出如下如所示。

Shape redCircle = new Circle(new RedCircle(),100,100,50);
redCircle.draw();

Log.e(TAG, "----------------------");
Shape greenCircle = new Circle(new GreenCircle(),300,300,100);
greenCircle.draw();

三、总结

桥接模式极大的提高了系统可扩展性,在两个变化维度中任意扩展一个维度,都不需要修改原有的系统,符合开闭原则,并且有着优秀的扩展能力,实现细节对客户透明。但是桥接模式的引入会增加系统的理解与设计难度,具体是否引入需要看具体的逻辑。

github地址:github.com/leewell5717…

四、参考

Java设计模式(十二)桥接模式