Java桥接模式

来源:互联网 发布:top100高频算法 编辑:程序博客网 时间:2024/06/07 05:35

桥接模式将定义与其实现分离。 它是一种结构模式。
桥接(Bridge)模式涉及充当桥接的接口。桥接使得具体类与接口实现者类无关。
这两种类型的类可以改变但不会影响对方。

当需要将抽象与其实现去耦合时使用桥接解耦(分离),使得两者可以独立地变化。这种类型的设计模式属于结构模式,因为此模式通过在它们之间提供桥接结构来将实现类和抽象类解耦(分离)。

这种模式涉及一个接口,作为一个桥梁,使得具体类的功能独立于接口实现类。两种类型的类可以在结构上改变而不彼此影响。

通过以下示例展示了桥接(Bridge)模式的使用,实现使用相同的抽象类方法但不同的网桥实现器类来绘制不同颜色的圆形。

实现实例

假设有一个DrawAPI接口作为一个桥梁实现者,具体类RedCircleGreenCircle实现这个DrawAPI接口。Shape是一个抽象类,将使用DrawAPI的对象。 BridgePatternDemo这是一个演示类,将使用Shape类来绘制不同彩色的圆形。实现结果图如下 -

第1步

创建桥实现者接口。

DrawAPI.java

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

第2步

创建实现DrawAPI接口的具体桥接实现者类。

RedCircle.java

public 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 + "]");   }}
Java

GreenCircle.java

public 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 + "]");   }}
Java

第3步

使用DrawAPI接口创建一个抽象类Shape
Shape.java

public abstract class Shape {   protected DrawAPI drawAPI;   protected Shape(DrawAPI drawAPI){      this.drawAPI = drawAPI;   }   public abstract void draw();    }
Java

第4步

创建实现Shape接口的具体类。

Circle.java

public class Circle extends Shape {   private int x, y, radius;   public Circle(int x, int y, int radius, DrawAPI drawAPI) {      super(drawAPI);      this.x = x;        this.y = y;        this.radius = radius;   }   public void draw() {      drawAPI.drawCircle(radius,x,y);   }}
Java

第5步

使用ShapeDrawAPI类来绘制不同的彩色圆形。

BridgePatternDemo.java

public class BridgePatternDemo {   public static void main(String[] args) {      Shape redCircle = new Circle(100,100, 10, new RedCircle());      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());      redCircle.draw();      greenCircle.draw();   }}
Java

第6步

验证输出结果,执行上面的代码得到结果如下 -

Drawing Circle[ color: red, radius: 10, x: 100, 100]Drawing Circle[  color: green, radius: 10, x: 100, 100]