桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。桥接模式通过将抽象部分与实现部分分离,使得它们可以独立地变化,从而提高了系统的灵活性和可扩展性。
下面是一个简单的桥接模式的示例:
首先,我们定义一个抽象类 Shape,它有一个 draw() 方法:
Java
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
public abstract void draw();
}
然后,我们定义一个实现类 DrawAPI,它有一个 drawCircle() 方法:
Java
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
接下来,我们定义两个实现类 RedCircle 和 GreenCircle,它们实现了 DrawAPI 接口:
Java
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: " + 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: " + y + "]");
}
}
最后,我们定义两个继承自 Shape 的实体类 Circle 和 Square,它们分别使用 RedCircle 和 GreenCircle 来绘制圆形和正方形:
Java
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);
}
}
public class Square extends Shape {
private int x, y, side;
public Square(int x, int y, int side, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.side = side;
}
public void draw() {
System.out.println("Drawing Square[ color: " + drawAPI.getClass().getSimpleName() + ", side: " + side + ", x: " + x + ", y: " + y + "]");
}
}
现在,我们可以使用桥接模式来绘制不同颜色的圆形和正方形:
Java
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());
Shape redSquare = new Square(100, 100, 10, new RedCircle());
Shape greenSquare = new Square(100, 100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
redSquare.draw();
greenSquare.draw();
}
}
输出结果如下:
Drawing Circle[ color: red, radius: 10, x: 100, y: 100]
Drawing Circle[ color: green, radius: 10, x: 100, y: 100]
Drawing Square[ color: RedCircle, side: 10, x: 100, y: 100]
Drawing Square[ color: GreenCircle, side: 10, x: 100, y: 100]