桥接模式是一种结构型设计模式,它可以将抽象部分与实现部分分离,使它们都可以独立地变化。桥接模式通过组合而不是继承来实现功能的扩展。
// 实现者接口
public interface DrawAPI {
void drawCircle(int x, int y, int radius);
}
// 具体实现者
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int x, int y, int radius) {
System.out.println("Drawing Circle[ color: red, x: " + x + ", y: " + y + ", radius: " + radius + "]");
}
}
// 抽象类
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;
}
@Override
public void draw() {
drawAPI.drawCircle(x, y, radius);
}
}