从类的实现中分离出抽象或者接口类,以便于这两个类能够互不相干,这种模式称作桥接模式。这种类型模式属于结构设计模式之一, 它通过提供了一个桥结构来分离具体的实现类和抽象类。
适用场合和优势:
- 想永久地分离抽象和实现类。
- 在多个对象中分享一个具体的实现类。
- 想去提高可扩展性。
- 从客户端哪里隐藏具体的实现。
具体分析一个简单的实例,看看它是如何实现桥接模式。
我们有一个接口DrawAPI, 桥接模式的实现类和它的之类RedCircle,GreenCircle。Shape是一个抽象类,适用了DreawAPI类的实例对象。BridgePatternDemo作为测试类,测试有关内容。UML类如下:
drawAPI接口类。
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
它的子类RedCircle、GreedCircle。
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
定义一个抽象类Shape。
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
抽象类的子类.
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
测试代码如下:
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}
测试结果:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]