将抽象部分与它的实现部分分离,使他们可以独立地变化。别名为:Handle/Body。
Bridge模式是构造型的设计模式之一。Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。
结构如下图所示:
例子代码如下:
//定义一个事物的抽象,维护对行为实现(Implementor)的引用
public abstract class Shape {
protected Drawing myDrawing;
abstract public void draw();
Shape(Drawing drawing) {
myDrawing = drawing;
}
public void drawLine() {
myDrawing.drawLine();
}
public void drawCircle() {
myDrawing.drawCircle();
}
}
public class Circle extends Shape{
Circle(Drawing drawing) {
super(drawing);
// TODO Auto-generated constructor stub
}
@Override
public void draw() {
// TODO Auto-generated method stub
myDrawing.drawCircle();
}
}
public class Rectangle extends Shape {
Rectangle(Drawing drawing) {
super(drawing);
// TODO Auto-generated constructor stub
}
@Override
public void draw() {
// TODO Auto-generated method stub
myDrawing.drawLine();
myDrawing.drawLine();
drawLine();
}
}
//实现部分的抽象
public abstract class Drawing {
public abstract void drawLine();
public abstract void drawCircle();
}
public class V1Drawing extends Drawing {
@Override
public void drawCircle() {
// TODO Auto-generated method stub
DP1.draw_a_circle();
}
@Override
public void drawLine() {
// TODO Auto-generated method stub
DP1.draw_a_line();
}
}
public class V2Drawing extends Drawing{
@Override
public void drawCircle() {
// TODO Auto-generated method stub
DP2.draw_a_circle();
}
@Override
public void drawLine() {
// TODO Auto-generated method stub
DP2.draw_a_line();
}
}
public class DP1 {
public static void draw_a_line() {
System.out.println("使用DP1的draw_a_line()画线");
}
public static void draw_a_circle() {
System.out.println("使用DP1的draw_a_circle()画圆");
}
}
public class DP2 {
public static void draw_a_line() {
System.out.println("使用DP2的draw_a_line()画线");
}
public static void draw_a_circle() {
System.out.println("使用DP2的draw_a_circle()画圆");
}
}
//测试类
public class BridgeClient {
public static void main(String args[]) {
Drawing draw1 = new V1Drawing();
Drawing draw2 = new V2Drawing();
Shape shape1 = new Rectangle(draw1);
shape1.draw();
Shape shape2 = new Circle(draw2);
shape2.draw();
Shape shape3 = new Circle(draw1);
shape3.draw();
}
}
输出结果:
使用DP1的draw_a_line()画线
使用DP1的draw_a_line()画线
使用DP1的draw_a_line()画线
使用DP2的draw_a_circle()画圆
使用DP1的draw_a_circle()画圆
Bridge模式的优点:
1 分离接口及其实现部分。
2 提高可扩充性。
3 实现细节对客户透明。
原文出自于:http://hi.baidu.com/isswangqing/item/126e4318bd99a708e65c36b3