目录

设计模式 - 桥梁模式( Bridge Pattern)

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

这种模式涉及一个接口,它充当一个桥梁,使具体类的功能独立于接口实现者类。 两种类型的类都可以在结构上进行更改而不会相互影响。

我们通过以下示例演示Bridge模式的使用,其中可以使用相同的抽象类方法但不同的桥实现者类以不同的颜色绘制圆。

实现 (Implementation)

我们有一个DrawAPI接口,它充当桥接器实现者和具体类RedCircleGreenCircle实现DrawAPI接口。 Shape是一个抽象类,将使用DrawAPI对象。 BridgePatternDemo ,我们的演示类将使用Shape类绘制不同的彩色圆圈。

桥模式UML图

Step 1

创建桥接器实现器接口。

DrawAPI.java

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

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

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

Step 3

使用DrawAPI接口创建抽象类Shape

Shape.java

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

Step 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);
   }
}

Step 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();
   }
}

Step 6

验证输出。

Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]
↑回到顶部↑
WIKI教程 @2018