橘子味的心
标题:Java桥接模式

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

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

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

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

实现实例

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

第1步

创建桥实现者接口。

DrawAPI.java

  1. public interface DrawAPI {
  2. public void drawCircle(int radius, int x, int y);
  3. }
  4. Java

第2步

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

RedCircle.java

  1. public class RedCircle implements DrawAPI {
  2. @Override
  3. public void drawCircle(int radius, int x, int y) {
  4. System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
  5. }
  6. }
  7. Java

GreenCircle.java

  1. public class GreenCircle implements DrawAPI {
  2. @Override
  3. public void drawCircle(int radius, int x, int y) {
  4. System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
  5. }
  6. }
  7. Java

第3步

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

  1. public abstract class Shape {
  2. protected DrawAPI drawAPI;
  3.  
  4. protected Shape(DrawAPI drawAPI){
  5. this.drawAPI = drawAPI;
  6. }
  7. public abstract void draw();
  8. }
  9. Java

第4步

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

Circle.java

  1. public class Circle extends Shape {
  2. private int x, y, radius;
  3.  
  4. public Circle(int x, int y, int radius, DrawAPI drawAPI) {
  5. super(drawAPI);
  6. this.x = x;
  7. this.y = y;
  8. this.radius = radius;
  9. }
  10.  
  11. public void draw() {
  12. drawAPI.drawCircle(radius,x,y);
  13. }
  14. }
  15. Java

第5步

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

BridgePatternDemo.java

  1. public class BridgePatternDemo {
  2. public static void main(String[] args) {
  3. Shape redCircle = new Circle(100,100, 10, new RedCircle());
  4. Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
  5.  
  6. redCircle.draw();
  7. greenCircle.draw();
  8. }
  9. }
  10. Java

第6步

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

  1. Drawing Circle[ color: red, radius: 10, x: 100, 100]
  2. Drawing Circle[ color: green, radius: 10, x: 100, 100]
  3. Java