我花了一些时间在维基百科上的这个Bridge模式示例中,但是,我仍然不明白这个桥梁模式试图解释什么。

interface DrawingAPI {
    public void drawCircle(double x, double y, double radius);
}

/** "ConcreteImplementor" 1/2 */
class DrawingAPI1 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
   }
}

/** "ConcreteImplementor" 2/2 */
class DrawingAPI2 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
   }
}

/** "Abstraction" */
interface Shape {
   public void draw();                                            // low-level
   public void resizeByPercentage(double pct);     // high-level
}

/** "Refined Abstraction" */
class CircleShape implements Shape {
   private double x, y, radius;
   private DrawingAPI drawingAPI;
   public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
       this.x = x;  this.y = y;  this.radius = radius;
       this.drawingAPI = drawingAPI;
   }

   // low-level i.e. Implementation specific
   public void draw() {
        drawingAPI.drawCircle(x, y, radius);
   }
   // high-level i.e. Abstraction specific
   public void resizeByPercentage(double pct) {
        radius *= pct;
   }
}

/** "Client" */
class Main {
   public static void main(String[] args) {
       Shape[] shapes = new Shape[2];
       shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
       shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());

       for (Shape shape : shapes) {
           shape.resizeByPercentage(2.5);
           shape.draw();
       }
   }
}

子类CircleShape构造函数采用4个args,在其draw()方法中,前3个args传递给第4个arg,它可以是DrawingAPI的任何子类。 那么这是否意味着使用桥接模式可以增加灵活性? 这个例子可以告诉我们更多的东西吗?

感谢!!!!

有帮助吗?

解决方案

为什么这有用的一个更具体的例子将使它更清楚。假设DrawingAPI1封装了您的图形驱动程序,而DrawingAPI2则为您的打印机驱动程序执行相同的操作。然后DrawingAPI是您的图形系统的通用API。它允许您将CircleShape绘制到显示器上并使用相同的代码在一张纸上打印,您只需要传递不同的DrawingAPI实现。但是,如果将DrawingAPI传递给Shape.draw()而不是将其传递给构造函数,则会更灵活,因为这样您就可以为监视器和打印机使用相同的对象图。

其他提示

  

子类CircleShape构造函数采用4个args,在其draw()方法中,前3个args传递给第4个arg,它可以是DrawingAPI的任何子类。那么这是否意味着使用桥接模式可以增加灵活性?这个例子可以告诉我们更多的东西吗?

这不仅仅是灵活性。 Bridge模式将抽象与实现分离,两者的区别可能不同

由于 CircleShape 使用组合来包含 DrawingAPI 而没有继承,因此可以将 DrawingAPI API替换为 DrawingAPI

Shape CircleShape 可以独立更改,而不依赖于 DrawingAPI

您可以在SE post下面找到有关Bridge模式的更多详细信息,它解释了不同的示例:

Bridge Pattern是否将抽象与实现分离?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top