欲开发一个绘图软件,要求使用不同的绘图程序绘制不同的图形。以绘制直线和圆形为例,对应的绘图程序如表 7.7 所示。
根据绘图软件的扩展性要求,该绘图软件将不断扩充新的图形和新的绘图程序。为了避免出现类爆炸的情况,现采用桥接(Bridge)模式来实现上述要求,得到如图 7.21 所示的类图。
桥接模式将抽象与其实现解耦,使它们都可以独立地变化。也就是说:将一组实现与另一组使用它们的对象分离。这里的实现指的是抽象类及其派生类用来实现自己的对象(而不是抽象类的派生类,这些派生类被称为具体类)。
【Java代码】
public abstract class Drawing {public abstract void drawLine(double xl,double yl,double x2,double y2);public abstract void drawCircle(double x,double y,double r);
}public class DP1 {public static void draw_a_line(double xl,double yl,double x2,double y2){/*代码省略 */}public static void draw_a_circle(double x,double y,double r){/*代码省略 */}
}public class DP2 {public static void drawLine(double xl,double x2,double yl,double y2) {/*代码省略 */}public static void drawCircle(double x,double y,double r) {/*代码省略 */}
}public class V1Drawing extends Drawing {public void drawLine(double xl,double yl,double x2,double y2) {DP1.draw_a_line();}public void drawCircle(double x,double y,double r) {DP1.draw_a_circle(x,y,z);}
}public class V2Drawing extends Drawing {public void drawLine(double xl,double yl,double x2,double y2){DP2.drawLine();}public void drawCircle(double x,double y,double r){DP2.drawCircle(x,y,z);}
}public abstract class Shape {protected Drawing _dp;public abstract void draw();Shape(Drawing dp) {_dp = dp;}public void drawLine(double xl,double yl,double x2,double y2) {dp.drawLine(xl,y1,x2,y2);}public void drawcircle (double x,double y,double r) { dp.drawcircle (x,y,r);}
}public class Rectangle extends Shape {private double _xl,_x2,_yl,_y2;public Rectangle(Drawing dp,double xl,double yl,double x2,double y2){/*代码省略 */}public void draw(){/*代码省略 */}
}public class Circle extends Shape {private double _x,_y,_r;public Circle(Drawing dp,double x,double y,double r){/*代码省略去 */}public void draw() {drawcircle(_x,_y,_r);}
}