use*_*340 5 java design-patterns bridge
我花了一些时间在维基百科的这个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()而不是将其传递给构造函数,则会更灵活,因为这样您就可以为监视器和打印机使用相同的对象图.