前言:主要解决在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活(组合替代继承)。下面这个例子使用桥接模式,在形状颜色都可以方便的扩展。
JAVA语言版桥接模式
创建颜色接口,以及颜色接口的实现类:
public interface DrawAPI {
void drawColor();
}
public class GreenCircle implements DrawAPI {
@Override
public void drawColor() {
System.out.println("使用绿色");
}
}
public class RedCircle implements DrawAPI {
@Override
public void drawColor() {
System.out.println("使用红色");
}
}
创建形状的抽象接口以及抽象接口的实现类:
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, redius;
public Circle(int x, int y, int redius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.redius = redius;
}
@Override
public void draw() {
System.out.println("画半径为" + redius + ",x为" + x + ",y为" + y);
drawAPI.drawColor();
}
}
使用 Shape 和 DrawAPI 类画出不同颜色的圆:
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redShape = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(100, 95, 10, new GreenCircle());
redShape.draw();
greenCircle.draw();
}
}
输出结果:
画半径为10,x为100,y为100
使用红色
画半径为10,x为100,y为95
使用绿色