介绍
桥接模式, 抽象化与实现化解耦,使得二者可以独立变化
UML
代码实现
public class BridgePatternDemo {
public static void main(String[] args) {
Shape shape1 = new Circle(new GreenCircle(), 1, 1, 1);
Shape shape2 = new Circle(new RedCircle(), 1, 2, 1);
shape1.draw();
shape2.draw();
}
}
/**
* 图形绘制
*/
public interface DrawApi {
void drawCircle(int radius, int x, int y);
}
/**
* 抽象的真正实现
*/
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 +"]");
}
}
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 abstract class Shape {
//抽象对外的暴露,DrawApi 是真正需要实现的方法
protected DrawApi drawApi;
public Shape(DrawApi drawApi){
this.drawApi = drawApi;
}
abstract public void draw();
}
/**
* 虽然继承了,但是没有真正实现
*/
class Circle extends Shape {
private final int x;
private final int y;
private final int redius;
public Circle(DrawApi drawApi,int x,int y,int radius) {
super(drawApi);
this.x = x;
this.y = y;
this.redius = radius;
}
@Override
public void draw() {
drawApi.drawCircle(redius, x, y);
}
}