Java设计模式-Java实现桥接模式(二)

2014-11-24 08:51:46 · 作者: · 浏览: 5
ngle2 r2 = new Rectangle2();
new Draw1(c1);
new Draw1(r1);
new Draw2(c2);
new Draw2(r2);
}
}
/************************************************************************************************************
* \ 好的,上述的代码运行正常,如果不需要维护的话,我们就不用管它拉~~ 但是,代码是一定要维护的,逃不过的宿命。 出现变化的地方可能是这样的:
* 1、出现了第三个库 2、画图系统需要画三角形 这个时候,我们再看看要完成这两个变化我们需要作的修改,就会发现,我要晕了
* (当一个程序员要晕的时候,也就是BUG要出现的时候了) \
************************************************************************************************************/
/************************************************************************************************************
* 好了,现在让我们使用Bridge模式来实现上面的系统
* Bridge模式最重要是把表示和实现分开
************************************************************************************************************/
/** 抽象出两个库中画圆,和画矩形的方法,为接口ShapeImp */
interface ShapeImp {
public void DrawCircle();
public void DrawRectangle();
}
/** 通过ShapeImp接口实现对库1的调用 */
class ShapeImp1 implements ShapeImp {
public void DrawCircle() {
dlib1.DrawCircle();
}
public void DrawRectangle() {
dlib1.DrawRectangle();
}
private DrawLib1 dlib1 = new DrawLib1();
}
/** 通过ShapeImp接口实现对库2的调用 */
class ShapeImp2 implements ShapeImp {
public void DrawCircle() {
dlib2.DrawCircle();
}
public void DrawRectangle() {
dlib2.DrawRectangle();
}
private DrawLib2 dlib2 = new DrawLib2();
}
/** 将"画圆"抽象到Circle类中 */
class Circle {
private ShapeImp shape;
public Circle(ShapeImp shape) {
this.shape = shape;
}
public void draw() {
shape.DrawCircle();
}
}
/** 将"画矩形"抽象到Rectangle类中 */
class Rectangle {
private ShapeImp shape;
public Rectangle(ShapeImp shape) {
this.shape = shape;
}
public void draw() {
shape.DrawRectangle();
}
}
/************************************************************************************************************
* \
*
* ClassName: Bridge
* Description: 使用"桥接"模式重新实现画图系统
*

*
* 再考虑下面的需求:
* 1.出现了第三个库
* 2.画图系统需要新增一个画三角形的方法
*

*
* 针对对一个需求,只需添加一个ShapeImg就可以了。
* 针对第二个需求,只需添加一个Triangle类就可以了。
* 可以看出来,变化不再造成混乱,只需要单独针对变化改动代码就行了。
* 也就是,变化被Bridge给分开了。
*
* @author gaojian email:gaojian@raiyi.com
* @version
* @since Ver 1.1
* @Date 2013 2013-10-28 下午1:58:13
* @see \
************************************************************************************************************/
class Bridge {
public void test() {
ShapeImp s1 = new ShapeImp1();
Circle c1 = new Circle(s1);
c1.draw();
Rectangle r1 = new Rectangle(s1);
r1.draw();
ShapeImp s2 = new ShapeImp2();
Circle c2 = new Circle(s2);
c2.draw();
Rectangle r2 = new Rectangle(s2);
r2.draw();
}
}
/** 测试使用桥接模式,和不使用桥接模式实现的画图系统 */
public class BridgeTest {
public static void main(String[] ar