? ? ? ? ? ? ? 桥接模式(Bridge Pattern)是一种结构型类型的设计模式,它将抽象部分与其实现部分分离,使它们可以独立变化。这种模式通过创建一个抽象类和实现类之间的桥接层来达到解耦的目的,允许在不修改原有接口的情况下扩展或更换实现。
? 桥接模式java示例代码:
// 实现接口
interface DrawingAPI {
void drawCircle(double x, double y, double radius);
}
// 具体实现类
class DrawingAPI1 implements DrawingAPI {
@Override
public void drawCircle(double x, double y, double radius) {
// 实现画圆形的逻辑1
}
}
class DrawingAPI2 implements DrawingAPI {
@Override
public void drawCircle(double x, double y, double radius) {
// 实现画圆形的逻辑2
}
}
// 抽象类
abstract class Shape {
protected DrawingAPI drawingAPI;
public Shape(DrawingAPI drawingAPI) {
this.drawingAPI = drawingAPI;
}
abstract void draw();
}
// 扩展抽象类
class CircleShape extends Shape {
private double x, y, radius;
public CircleShape(DrawingAPI drawingAPI, double x, double y, double radius) {
super(drawingAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
void draw() {
drawingAPI.drawCircle(x, y, radius);
}
}
// 客户端代码
public class BridgePatternDemo {
public static void main(String[] args) {
Shape circle1 = new CircleShape(new DrawingAPI1(), 10, 10, 5);
Shape circle2 = new CircleShape(new DrawingAPI2(), 15, 15, 8);
circle1.draw(); // 使用DrawingAPI1绘制圆
circle2.draw(); // 使用DrawingAPI2绘制圆
}
}