什么是桥接模式?
桥接模式是一种结构型模式,用于把抽象和实现分离。它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。
为什么使用桥接模式?
种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。
桥接模式的使用场景?
1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。
2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。
如何实现?
我们先看一个简单的接口和两个实现:
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
public class GreenCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
public class RedCircle implements DrawAPI{
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
一个画圆的接口和两个不同颜色的实现类。
桥接类:
public abstract class Shape {
protected DrawAPI api;
protected Shape(DrawAPI api){
this.api = api;
}
public abstract void draw();
}
public class Circle extends Shape{
private int x, y, redius;
private DrawAPI api;
public Circle(int x,int y,int redius,DrawAPI api){
super(api);
this.x = x;
this.y = y;
this.redius = redius;
}
public void draw() {
api.drawCircle(redius,x,y);
}
}
调用客户端:
public class Client {
public static void main(String[] args) {
Shape shape1 = new Circle(100,100, 10, new RedCircle());
Shape shape2 = new Circle(100,100, 10, new GreenCircle());
shape1.draw();
shape2.draw();
}
}