1. 概念
桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立变化,而不会相互影响。桥接模式通过组合的方式,将多个维度的变化分离开来,从而提高系统的灵活性和可扩展性。
在桥接模式中,主要包含以下角色:
-
抽象部分(Abstraction):定义抽象类接口,它维护一个指向实现部分的引用对象,并定义了基于实现部分的高级操作。
-
扩展抽象部分(Refined Abstraction):继承自抽象部分,扩展了抽象部分的接口,可以实现更复杂的业务逻辑。
-
实现部分接口(Implementor):定义实现部分的接口,该接口不一定与抽象部分完全一致,但是通常提供基本的操作方法供具体实现类实现。
-
具体实现部分(Concrete Implementor):实现部分接口的具体实现类,提供具体的业务逻辑。
桥接模式的关键在于将抽象部分和实现部分分离,使得它们可以独立变化。通过这种方式,我们可以在不修改原有代码的情况下,动态地替换抽象部分或实现部分的具体实现,从而灵活地应对需求变化和系统扩展。
2. 示例
// 实现部分的接口
interface DrawingAPI {
void drawCircle(int x, int y, int radius);
}
// 具体实现部分:画图API A
class DrawingAPIA implements DrawingAPI {
public void drawCircle(int x, int y, int radius) {
System.out.printf("API A - Drawing circle at (%d:%d) with radius %d\n", x, y, radius);
}
}
// 具体实现部分:画图API B
class DrawingAPIB implements DrawingAPI {
public void drawCircle(int x, int y, int radius) {
System.out.printf("API B - Drawing circle at (%d:%d) with radius %d\n", x, y, radius);
}
}
// 抽象部分
abstract class Shape {
protected DrawingAPI drawingAPI;
protected Shape(DrawingAPI drawingAPI) {
this.drawingAPI = drawingAPI;
}
public abstract void draw();
}
// 扩展抽象部分:圆形
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawingAPI drawingAPI) {
super(drawingAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawingAPI.drawCircle(x, y, radius);
}
}
// 示例
public class BridgePatternExample {
public static void main(String[] args) {
DrawingAPI apiA = new DrawingAPIA();
DrawingAPI apiB = new DrawingAPIB();
Shape circle1 = new Circle(1, 2, 3, apiA);
circle1.draw(); // 输出:API A - Drawing circle at (1:2) with radius 3
Shape circle2 = new Circle(5, 7, 10, apiB);
circle2.draw(); // 输出:API B - Drawing circle at (5:7) with radius 10
}
}
在这个示例中,DrawingAPI
定义了画图的接口,DrawingAPIA
和 DrawingAPIB
分别是不同的画图实现。Shape
是抽象部分,Circle
是扩展抽象部分,它们可以基于不同的 DrawingAPI
实现画图的功能。这样,我们可以动态地将 Circle
对象关联到不同的 DrawingAPI
上,实现了抽象部分和实现部分的解耦。