将内外系统分离的设计模式。
创建一个 API 工具集,工具集有其各自实现。外部模块调用时,直接使用接口调用具体方法。
“打包 API 类整个交给外部模块调用”
- DrawAPI 像是一个“桥”,提供对外接口。
- Shape 无需关注 API 的具体实现方式,只需要将 DrawAPI 独立实例化即可。
- 核心在于 Demo 直接调用 RedCircle 和 GreenCircle 类传递给 Shape,并在 Shape 内部实例化
- 由此,RedCircle 内部的 API 便可独立于 Shape 中的方法变化
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
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 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);
}
}